1

For example, drawing a black circle followed by a white circle of the same radius in the same location leaves behind a grey residue. I'm assuming it's not drawing the circles the same, per pixel, each time.

I wish to have a circle move around in a canvas but in order to do this I will need to overwrite the circle before drawing it in its new location.

HTML:

<canvas id="myCanvas" width="960" height="540" style="border:1px solid #000000;"></canvas>

Javascript:

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);

context.beginPath();
context.arc(100, 100, 40, 0, 2 * Math.PI);
context.strokeStyle = "black";
context.stroke();

context.beginPath();
context.arc(100, 100, 40, 0, 2 * Math.PI);
context.strokeStyle = "white";
context.stroke();
David Bandel
  • 252
  • 3
  • 19

1 Answers1

1

You will need to redraw the background every time.

function drawBg() {
    context.fillStyle = "white";
    context.fillRect(0, 0, canvas.width, canvas.height);
}

drawBg();
context.beginPath();
context.arc(100, 100, 40, 0, 2 * Math.PI);
context.strokeStyle = "black";
context.stroke();

drawBg();
context.beginPath();
context.arc(100, 100, 40, 0, 2 * Math.PI);
context.strokeStyle = "white";
context.stroke();

I did some research into this phenomenon. I think the cause is anti-aliasing.

  1. Can I turn off antialiasing on an HTML <canvas> element?
  2. How to anti-alias clip() edges in html5 canvas under Chrome Windows?

It seems you can't draw pixel-perfect hard-edged circles on the html canvas with arc() and vector graphics.

Community
  • 1
  • 1
csirmazbendeguz
  • 598
  • 4
  • 13
  • Does this mean that if I have multiple circles moving around I will need to erase the entire canvas and redraw each circle each time? – David Bandel Mar 15 '17 at 21:41
  • No, if you have more circles moving around then first you draw the background then you draw all the circles. But you will have this phenomena though. – csirmazbendeguz Mar 15 '17 at 21:51
  • I see. So I'll do this drawBg each frame. It's how I should have been doing it from the start. For some reason I was going to manage circles independent which is messy. Your way fixes it. Thank you for your help – David Bandel Mar 15 '17 at 21:55