这是一种方法。创建一个数组来保存你的块,以及一个用于盒子的 Block 对象。然后我创建两个方法,update 和 render,它们更新框并将其绘制到画布上。
块对象
function Block(x,y,width,height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Block.prototype.update = function(){
if(this.y < 360){
this.y+=dy
}else{
this.y = 0;
}
};
Block.prototype.render = function(){
context.fillRect(this.x, this.y, this.width, this.height);
};
检查时间是否达到阈值
至于创建独立于帧速率的新块,您只需进行时间检查,看看自上次创建块以来是否经过了 1 秒。
if(+new Date() > lastTime + minWait){
lastTime = +new Date();
// add a new block
blocks.push(new Block(Math.random()*300, 0,20,20));
}
基本上这是如何工作的,如果当前时间大于上次时间 + 1 秒,它将创建一个新时间,并将 lastTime 重置为当前时间。
附加信息
我强烈建议您查看requestAnimationFrame,这是进行任何类型画布渲染的正确且事实上的方式。
完整来源
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
//update and animate the screen
var FPS = 60;
setInterval(function() {
//update();
draw();
}, 1000/FPS);
var dy = 5,
blocks = [],
minWait = 1000,
lastTime = +new Date();
function Block(x,y,width,height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Block.prototype.update = function(){
if(this.y < 360){
this.y+=dy
}else{
this.y = 0;
}
};
Block.prototype.render = function(){
context.fillRect(this.x, this.y, this.width, this.height);
};
//draw the screen
function draw() {
if(+new Date() > lastTime + minWait){
lastTime = +new Date();
blocks.push(new Block(Math.random()*300, 0,20,20));
}
context.clearRect(0,0,canvas.width, canvas.height);
blocks.forEach(function(e){
e.update();
e.render();
});
};