【问题标题】:clearRect issue in animation动画中的 clearRect 问题
【发布时间】:2014-02-01 13:21:23
【问题描述】:

我有 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);

它有效,但它不是合乎逻辑的方式

【问题讨论】:

  • 这似乎是亚像素渲染的问题。您的 this.x 和 this.y 值是否保证为整数或它们有时会浮动?
  • +1 for @ZachBabb,还有这个额外的问题:宽度/高度是偶数还是奇数?
  • 是的,宽度高度 x 和 y 都是整数,只有当我在 0rad 上下没有剩余时图像的角度不同于 0 时才会发生这种情况

标签: html canvas frame


【解决方案1】:

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

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

尝试改变这一行:

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);

【讨论】:

  • 好的,所以我必须为别名像素添加一些额外的宽度和高度,没有其他解决方案吗?
  • @user3191059 您可以尝试使用属性ctx.imageSmoothingEnabled = false 关闭图像的插值,但它似乎不适用于旋转(上次我检查过),只能缩放/调整大小。
猜你喜欢
  • 1970-01-01
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2017-10-13
  • 2012-07-01
相关资源
最近更新 更多