在画布上的模糊的方形该怎么办?

时间:2014-08-26 19:10:07

标签: javascript html5 canvas html5-canvas

为什么画布上的方形模糊?如果你仔细观察,你会发现图像模糊不清。为什么会发生这种情况,我该如何解决? 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();

2 个答案:

答案 0 :(得分:2)

确保你的x,y是整数:

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

答案 1 :(得分:1)

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

希望它有所帮助。