简体   繁体   中英

Issue with erasing canvas shape

I am working on a doodle in canvas,

I am running into an issue where when I erase the object by overdrawing it with the background color I am left with an outline of the original shape. 在此处输入图片说明

Here is the code I am using

and yes I am not using clear rect because the circles can overlap.

    function erase(eraseColor) {
    ctx.fillStyle = ctx.strokeStyle = eraseColor || "#FFFFFF";
    drawCircle();
    ctx.fillStyle = ctx.strokeStyle = fillColor;
}

function drawCircle() {
    ctx.beginPath();
    ctx.arc(x, y, rad, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fill();
}

I believe this is due to anti-aliasing. The effect should not appear on shapes that do not require anti-aliasing (like rectangles). Draw the erasing circle a few pixels bigger (one should do).

In case the question comes up: you cannot turn off anti-aliasing for canvas .

As Ray suggested you should think about using frame based animation, optimized by using dirty rectangles.

To do this you simply flag a rectangle as dirty, if any pixels within it have changed (eg due to animation). You then clear the rectangle on the canvas ( clearRect ) and set it as a clipping rectangle ( clip ). Then you iterate through all elements that are displayed on your canvas and check wether they overlap with your dirty rectangle. If so, you draw the element, if not you skip to the next element.

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