【问题标题】:Blurred square on canvas. What to do?画布上的模糊正方形。该怎么办?
【发布时间】:2014-10-20 05:30:49
【问题描述】:

为什么在画布上模糊正方形?如果您仔细观察,您会发现图像模糊不清。为什么会发生这种情况,我该如何解决? jsfiddle

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var mx=0,my=0;
var rect = {
x: 0,
y: 0,
w: 30,
h: 30,
s: 5
}
rect.update = function(x,y){
this.targetX = x;
this.targetY = y;
var tx = this.targetX - this.x;
var ty = this.targetY - this.y;
var dist = Math.sqrt(tx*tx+ty*ty);
this.velX = (tx/dist)*this.s;
this.velY = (ty/dist)*this.s;
if(dist>this.w/2){
this.x += this.velX;
this.y += this.velY;
}
}
canvas.addEventListener('click',function(e){
mx = e.clientX;
my = e.clientY;
});
function paint(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(rect.x,rect.y,rect.w,rect.h);
ctx.fillStyle = 'red';
rect.update(mx,my);
window.requestAnimationFrame(paint);
};
paint();

【问题讨论】:

    标签: javascript html canvas html5-canvas


    【解决方案1】:

    确保你的 x,y 是整数:

    this.x = parseInt(this.x+this.velX);
    this.y = parseInt(this.y+this.velY);
    

    【讨论】:

    • 我建议更改绘图代码,而不是定位。如果您将paint() 函数中的行更改为:ctx.fillRect(Math.floor(rect.x),Math.floor(rect.y),rect.w,rect.h);,那么您仍然可以有小数位置,但该框仍然没有消除锯齿。
    • @zrneely 当然,听起来不错。重要的是绘制是在整数边界上完成的。
    【解决方案2】:

    您应该像@markE 所说的那样将您的对象坐标保持为整数,并且您也可以尝试将 imageSmoothing 设置为 false: disable image smoothing

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 2011-08-07
      • 1970-01-01
      • 2016-08-05
      • 2013-05-24
      相关资源
      最近更新 更多