首页 > 解决方案 > 为什么调用 stroke 会导致这个元素被绘制在 HTML 画布上?

问题描述

我在一堆填充的蓝色圆圈上绘制一个白色矩形。这是填充圆圈的代码:

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();
  }

这是调用上述函数的代码:

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]);
        }
      }
    }

最后,这是绘制矩形的代码:

   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);
      }

当我第一次调用draw()thenwinMessage()时,白色矩形的其中一个圆圈的轮廓显示出来(见图)。我不确定为什么没有清除中风队列。请使用我提供的jsbin更仔细地查看问题。

漏洞

JSBIN

标签: javascripthtmlcanvasfillstroke

解决方案


您绘制的最后一个圆圈仍然由画布上下文保存,并且在您调用ctx.stroke(). 要清除它,您需要ctx.beginPath()在绘制矩形之前添加一个。

或者,您可以ctx.strokeRect()改用,然后跳过ctx.stroke().

更新小提琴:https ://jsfiddle.net/r7bcmLpq/4/


推荐阅读