shurup
shurup

Reputation: 871

Why does calling stroke result in this element being drawn on HTML canvas?

I am drawing a white rectangle on top of a bunch of filled blue circles. This is the code for filling a circle:

function fillCircle(color, radius, x, y){
    console.log("New Circle With Color: " + color + " Radius: " + radius + "X: " + x + "Y: " + y);
    ctx.save();
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.restore();
  }

This is the code that calls the above function:

var draw = function(){
      //draws map with ships
      for(var k = 1; k < 6; k++){
        for(var i = 0; i < 24; i++){
          var point = polarToReal(k, i * Math.PI / 12);
          fillCircle("blue", 4, point[0], point[1]);
        }
      }
    }

Finally, here is the code that draws a rectangle:

   function winMessage(color, text){
        ctx.fillStyle = "white";
        ctx.fillRect(WIDTH/4, HEIGHT/4, WIDTH/2, HEIGHT/2)
        ctx.font = WIDTH/20+"px Arial";
        ctx.strokeStyle = "black";
        ctx.rect(WIDTH/4, HEIGHT/4, WIDTH/2, HEIGHT/2);  
        ctx.stroke();
        ctx.fillStyle = color;
        ctx.textAlign = "center";
        ctx.fillText(text, WIDTH/2, HEIGHT/2);
      }

When I first call draw() and then winMessage(), the white rectangle has the outline of one of the circles showing through (see image). I am not sure why the stroke queue isn't cleared. Please use the jsbin I provided to see the issue more closely.

Bug

JSBIN

Upvotes: 2

Views: 496

Answers (1)

Steve
Steve

Reputation: 10886

The last circle you draw is still saved by the canvas context, and it's being redrawn when you call ctx.stroke(). To clear it, you need to add a ctx.beginPath() before you draw your rectangle.

Alternatively you can use ctx.strokeRect() instead, and skip ctx.stroke().

Updated fiddle: https://jsfiddle.net/r7bcmLpq/4/

Upvotes: 3

Related Questions