Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw circles in HTML5 canvas with text in them

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);
        }
    });
like image 264
user1779563 Avatar asked Jan 26 '13 17:01

user1779563


1 Answers

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>
like image 51
Denys Séguret Avatar answered Oct 28 '22 00:10

Denys Séguret