简体   繁体   English

删除画布形状的问题

[英]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 . 万一出现问题: 您不能关闭canvas的抗锯齿功能

As Ray suggested you should think about using frame based animation, optimized by using dirty rectangles. 正如Ray所建议的那样,您应该考虑使用基于帧的动画,该动画通过使用脏矩形进行了优化。

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 ). 然后,清除画布上的矩形( clearRect )并将其设置为剪贴矩形( 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. 如果是这样,则绘制该元素,否则,请跳到下一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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