动画中的clearRect问题

时间:2014-01-13 17:16:31

标签: html canvas frame

我遇到了clearRect的问题,我有一个图像,你可以上下移动,并且跟随慕斯的角度,但在动画的某些帧中,clearRect让前一个图像状态的一个小边缘('this'对图像的引用和'ctx'是2d上下文,在重新绘制新坐标图像之前,每个帧调用'this.clear()'。

this.clear = function(){
    game.ctx.save();
    game.ctx.translate(this.x+this.width/2, this.y+this.height/2);//i translate to the old image center
    game.ctx.rotate(this.angle);//i rotate the context to the good angle
    game.ctx.clearRect(this.width/-2, this.height/-2, this.width, this.height);//i clear the old image
    game.ctx.restore();
};

如果我用

替换clearRect行
game.ctx.clearRect(this.width/-2-1, this.height/-2-1, this.width+2, this.height+2);

它有效,但不是逻辑方式

1 个答案:

答案 0 :(得分:0)

问题是你只是在宽度/高度的一半处清除,而不是位置减去宽度/高度的一半。

关于消除锯齿:当您进行旋转时,无论原始位置是整数值,都会有抗锯齿像素。这是因为在像素相对位置通过变换矩阵之后,它们的偏移在大多数情况下将是浮点值。

尝试更改此行:

game.ctx.clearRect(this.width/-2, this.height/-2, this.width, this.height);

反过来包括对抗锯齿像素的补偿(我将分割线条以便清晰):

game.ctx.clearRect(this.x - this.width/2 - 1,   /// remember x and y
                   this.y - this.height/2 - 1,
                   this.width + 2, 
                   this.height + 2);
相关问题