8

Seemed simple enough to draw circles and text in an HTML5 canvas, but I get non-intuitive behavior. The circles get drawn nice and pretty, then the more circles I draw, the older circles become more and more octagonal shaped. Very strange to me... Also, the text disappears from the old circles and only appears on the last circle drawn. What's the proper way to do this with canvases?

    $("#circles_container").on("click", "#circles_canvas", function(event) {
        var canvas = document.getElementById('circles_canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            var w = 16;
            var x = event.pageX;
            var y = Math.floor(event.pageY-$(this).offset().top);
            ctx.fillStyle = "rgb(200,0,0)";
            ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
            ctx.fill();

            ctx = canvas.getContext("2d");
            ctx.font = '8pt Calibri';
            ctx.fillStyle = 'white';
            ctx.textAlign = 'center';
            ctx.fillText('0', x, y+3);
        }
    });
user1779563
  • 770
  • 3
  • 7
  • 13

1 Answers1

12

Just add this near the start of your function :

ctx.beginPath();

You were drawing a path always longer.

Demo in Stack Snippets & JS Fiddle (click on the canvas)

var canvas = document.getElementById('circles_canvas');
canvas.addEventListener("click", function(event) {
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    var w = 16;
    var x = Math.floor(event.pageX-this.offsetLeft);
    var y = Math.floor(event.pageY-this.offsetTop);
    
    ctx.beginPath();
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
    ctx.fill();

    ctx.font = '8pt Calibri';
    ctx.fillStyle = 'white';
    ctx.textAlign = 'center';
    ctx.fillText('0', x, y+3);
  }
})
canvas {
  border: 1px solid black;
}
<h1>Click Canvas Below</h1>
<canvas id="circles_canvas"></canvas>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758