我编写了以下 1000 个边界方块演示,以测试 HTML5 画布的功能。起初它运行良好,但几秒钟后 fps 明显下降。我不确定为什么。任何指针将不胜感激。
var c = document.getElementById("canvas");
var context = c.getContext("2d");
var WIDTH = 600;
var HEIGHT = 800;
c.width = WIDTH;
c.height = HEIGHT;
image = loadImage("square.png");
function loadImage(imageName){
var i = new Image();
i.src = imageName;
return i;
}
function clear(){
context.fillStyle = "#d0e7f9";
context.rect(0,0,WIDTH,HEIGHT);
context.fill();
}
clear();
var SpriteList = [];
var Sprite = (function() { //javascript class(?)... shredders
function Sprite(){ //constructor
this.x = Math.random()*WIDTH;
this.y = Math.random()*HEIGHT;
this.vx = Math.random()*10;
this.vy = Math.random()*10;
SpriteList.push(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;
}
};
return Sprite;
})();
for (var i = 0;i<1000;i++){
new Sprite();
}
function draw(){
clear();
for (i in SpriteList)
{
var s = SpriteList[i];
s.update();
context.drawImage(image, s.x, s.y);
}
}
setInterval(draw,1000/60);