HTML5 Canvas中的对象在动画期间留下痕迹

时间:2017-09-05 10:33:02

标签: javascript html5 animation html5-canvas

我正在尝试为html5画布设置动画,并为其中的每个元素创建了对象。首先,我在一个单独的javascript文件上调用对象,绘制图像,然后运行一个gameLoop来处理它们的运动/动画,如下所示:

//Draws a canvas on the screen
spiel.drawCanvas(800,600, "#FFF000");

//Creates a new Rectangle object, then calls the draw function inside it
var rect1 = new spiel.Rectangle(10,10, 100,100, "#FF00FF");
rect1.draw();

//Creates a new circle object, then calls the draw function inside it
var circ1 = new spiel.Circle(300, 300, 30, "#00FF00");
circ1.draw();

//Calls the gameLoop function, which executes a requestAnimationFrame, and then executes what is inside the function argument every frame
spiel.gameLoop(function(){
//Moves the rectangle object downwards with a velocity of 2 pixels per iteration
rect1.moveDown(2);

//Moves the circle object to the left with a velocity of 1 pixel per iteration
circ1.moveLeft(1);
});

这些对象/函数存储在另一个javascript文件中。以下是一些代码:

GameLoop

gameLoop : function gameLoop(func){
requestAnimationFrame(function(){gameLoop(func); func();});
},

矩形绘制和动画

//Draws a recatngle on the screen
this.draw = function(){
c.fillStyle = this.color;
c.fillRect(this.posX, this.posY, this.width, this.height);
}

//These functions move the created rectangle in a certain direction
this.moveLeft = function moveLeft(velocity){
    this.velocity = velocity;
    c.clearRect(this.posX, this.posY, this.width, this.height);
    this.posX -= this.velocity;
    c.fillStyle = this.color;
    c.fillRect(this.posX, this.posY, this.width, this.height);
}

圆形绘制和动画

//Draw the circle on the screen
this.draw = function(){
  c.beginPath();
  c.arc(this.posX, this.posY, this.radius, 0, 2 * Math.PI, false);
  c.fillStyle = this.color;
  c.fill();
  c.closePath();
}

//These functions move the circlular object on certain directions
this.moveLeft = function moveLeft(velocity){
  this.velocity = velocity;
  c.save();
  c.globalCompositeOperation = 'destination-out';
  c.beginPath();
  c.arc(this.posX, this.posY, this.radius, 0, 2 * Math.PI, false);
  c.fill();
  c.restore();

  this.posX -= this.velocity;

  c.beginPath();
  c.arc(this.posX, this.posY, this.radius, 0, 2 * Math.PI, false);
  c.fillStyle = this.color;
  c.fill();
  c.lineWidth = 0;
  c.strokeStyle = this.color;
  c.stroke();
  c.closePath();
}

我的问题是,当我测试它时,这些对象会在画布上留下痕迹,特别是圆圈。我拍了一下画布的截图:

Canvas Screenshot

造成这种情况的原因是什么?我该怎么做才能解决它?

非常感谢您的阅读,并提前感谢您的回答!

编辑:我在创建画布时添加了c.translate(1, 1);,现在不再出现矩形对象离开的轨迹,但是圆形轨迹仍然存在。通过试验不同的速度,在我看来,圆形离开的痕迹可能是它的笔划/边界。是否有可能没有清除笔划/边框?

0 个答案:

没有答案