简体   繁体   中英

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/

Another issue, clearRect() behaves differently on Firefox when the canvas is rotated, by clearing the whole unrotated space used by the rotated rectangle.
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM