[英]How to properly clear a rotated HTML5 canvas context?
I need to clear a rotated rectangle and draw it again on a canvas, either at the same place or elsewhere.我需要清除一个旋转的矩形并在画布上再次绘制它,无论是在同一个地方还是在其他地方。 The problem is, the cleared part doesn't match the rectangle's bounds, leaving dirty bits behind.问题是,清除的部分与矩形的边界不匹配,留下脏位。
var cvs = document.getElementById('testcanvas');
var ctx = cvs.getContext('2d');
var rectColor = 'green';
var x = 300;
var y = 10;
var width = 200;
var height = 150;
var rotation = 0;
setInterval(animate, 100);
function animate(){
clearRect();
update();
drawRect();
}
function clearRect(){
ctx.save();
ctx.rotate(rotation);
ctx.clearRect(x, y, width, height);
ctx.restore();
}
function update(){
rotation += 0.1;
x++;
}
function drawRect(){
ctx.save();
ctx.fillStyle = rectColor;
ctx.rotate(rotation);
ctx.fillRect(x, y, width, height);
ctx.restore();
}
http://jsfiddle.net/MFz2z/15/ http://jsfiddle.net/MFz2z/15/
Another issue, clearRect() behaves differently on Firefox when the canvas is rotated, by clearing the whole unrotated space used by the rotated rectangle.另一个问题是,clearRect() 在画布旋转时在 Firefox 上的行为不同,通过清除旋转矩形使用的整个未旋转空间。
http://jsfiddle.net/MFz2z/17/ http://jsfiddle.net/MFz2z/17/
Is there any workaround to this, other than clearing the whole canvas and drawing everything again ?除了清除整个画布并重新绘制所有内容之外,是否有任何解决方法? I use Chrome 22 and Firefox 15.0.1.我使用 Chrome 22 和 Firefox 15.0.1。
It could be due to the anti-aliasing of the pixels that create the extra tidbits.这可能是由于像素的抗锯齿造成了额外的花絮。
You could use this http://jsfiddle.net/MFz2z/28/ and basically clear 1 more pixel from each side.你可以使用这个http://jsfiddle.net/MFz2z/28/并且基本上从每侧清除 1 个像素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.