我用canvas和javascript创建了一个小型弹跳盒子演示。每个“盒子”类处理自己的更新和渲染。然而,我的问题在于在绘制下一帧之前清除画布。当盒子移动时,它可以很好地清除,但是在撞到墙壁后会留下痕迹。这里有一个fiddle链接:https://jsfiddle.net/dzuvL7ph/1/
以下是我的代码:
我猜这与
function init(){
window.box1 = new Box(50, 'red', 0, 0);
window.box2 = new Box(50, 'blue', 400, 20);
requestAnimationFrame(update);
}
function update() {
window.box1.update();
window.box2.update();
requestAnimationFrame(update);
requestAnimationFrame(render);
}
function render() {
window.box1.render();
window.box2.render();
}
// -------------------------------------------------------------------------------------------------------
// --
// -------------------------------------------------------------------------------------------------------
var Box = function(dimensions, color, x, y){
this.width = dimensions;
this.height = dimensions;
this.x = x;
this.y = y;
this.velocityX = 10;
this.velocityY = 10;
this.color = color;
this.context = document.getElementById('canvas').getContext('2d');
this.update = function(){
this.x += this.velocityX;
this.y += this.velocityY;
this.collisionCheck();
};
this.render = function(){
this.context.fillStyle = this.color;
this.context.clearRect(this.x - this.velocityX, this.y - this.velocityY, this.width, this.height);
this.context.fillRect(this.x, this.y, this.width, this.height);
};
this.collisionCheck = function(){
if(this.y > 600 - this.height || this.y < 0)
this.velocityY *= -1;
if(this.x > 800 - this.width || this.x < 0)
this.velocityX *= -1;
};
};
我猜这与
this.context.clearRect(this.x - this.velocityX, this.y - this.velocityY, this.width, this.height);
有关,但我搞不清我错在哪里了。
this.context.clearRect (0, 0, canvas.width, canvas.height)
来清除整个画布。但这会影响性能... - Rayon