Question

I'm trying to figure out why drawing a shape, then drawing over it in a new color (as though to highlight it), and then re-drawing the original (un-highlighting it) is leaving traces of the highlighted color.

I've reproduced the issue in this fiddle. The wedge is drawn in a light-blue color. There's a red button that'll draw over it in red, then another button that re-draws the original shape. All parameters are identical (except for the color), but yet after clicking the button to reset the color, there's a faint trace of red over the wedge.

Before:

enter image description here

After:

enter image description here

Here's the relevant code:

drawWedge(250, 250, 200, 0, 18, "rgb(150, 254, 223)");

$("#red").click(function () {
    drawWedge(250, 250, 200, 0, 18, "rgb(255, 0, 0)");
});

$("#back").click(function () {
    drawWedge(250, 250, 200, 0, 18, "rgb(150, 254, 223)");
});

function d2r(degrees) {
    return degrees * (Math.PI / 180.0);
}

function drawWedge(centerX, centerY, r, start, end, color) {
    context.beginPath();
    context.moveTo(centerX, centerY);
    context.arc(centerX, centerY, r, d2r(start), d2r(end), false);
    context.closePath();
    context.fillStyle = color;
    context.fill();
}
Was it helpful?

Solution

When drawing on canvas, it just keeps stacking things on top of each other until you clear it. The easiest way to clear it is ctx.clearRect(0,0,width,height)

I put that in your drawWedge function here:

http://jsfiddle.net/X7deh/1

OTHER TIPS

This question was already answered, but I wanted to give a little more thorough explanation.

enter image description here

When you draw at a diagonal, your passing through "parts" of pixels (show in my example). So what does the browser do to the part of the pixel outside of the shape? It uses anti-aliasing (anti-aliasing is always on by default for browsers) to color the rest of the pixel (if you didnt have anti-aliasing the line would look jagged). If you notice, the faint trace of red is not a bright red because its getting blended due to anti-aliasing. And the reason you see it is because when you draw your shape on the canvas, the faint trace of red is not part of your shape, its part of the pixel on the outside of your shape.

Now as the answer mentioned, you can call clearRect to clear the canvas. However, you should read this SO question as it explains things in more detail (the selected answer is not as good as the second answer). Also, ever wonder why they call it a "canvas"? Think of an actual art canvas used by artists, once they paint on the canvas there is no way to take it off unless you get a new canvas or paint over it!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top