代码存在一些问题,但发生这种情况的主要原因是以下代码:
此代码将要求您使用beginPath()
:
function clear(){
context.fillStyle = "#d0e7f9";
context.beginPath();
context.rect(0,0,WIDTH,HEIGHT); /// this will require beginPath();
context.fill();
}
或者为了避免这种情况,您可以简单地修改代码来执行此操作:
function clear(){
context.fillStyle = "#d0e7f9";
context.fillRect(0,0,WIDTH,HEIGHT); /// this does not require beginPath();
}
这里现场演奏小提琴 http://jsfiddle.net/AbdiasSoftware/trSe4/
/// use a var here
var image = loadImage("square.png");
/// your image loader is missing - image may not show up
function loadImage(imageName){
var i = new Image();
i.onload = nextStep; /// something like this
i.src = imageName;
return i;
}
var SpriteList = [];
/// create this as an object
function Sprite(){ //constructor
this.x = Math.random()*WIDTH;
this.y = Math.random()*HEIGHT;
this.vx = Math.random()*10;
this.vy = Math.random()*10;
return this;
}
Sprite.prototype.update = function(){
this.x += this.vx;
this.y += this.vy;
if (this.x<0 || this.x>WIDTH){
this.vx *= -1;
}
if (this.y<0 || this.y>HEIGHT){
this.vy *= -1;
}
};
/// separate pushing of the instances
for (var i = 0;i<1000;i++){
SpriteList.push(new Sprite());
}
var oldTime = 0;
function draw(timeElapsed){ /// in milliseconds
clear();
var diffTime = timeElapsed - oldTime;
/// use vars here too
for (var i = 0, s; s = SpriteList[i]; i++ )
{
s.update();
context.drawImage(image, s.x, s.y);
}
oldTime = timeElapsed;
/// use rAF here
requestAnimationFrame(draw);
}
draw(0); /// start
The setInterval
如果浏览器在您给出的时间预算内处理精灵的速度不够快,可能会导致整个事情堆栈调用。
通过使用 rAF,浏览器只会在可以的情况下请求帧,即使这意味着较低的帧速率 - 至少不会锁定/减慢浏览器的速度。
(因为您没有提供指向您正在使用的图像的链接,所以我用临时画布替换了它 - 您仍然需要考虑onload
实际图像的事件处理程序)。