Javascript 为什么调用stroke会导致在HTML画布上绘制此元素?
我正在一堆蓝色的圆圈上面画一个白色的长方形。这是填充圆的代码:Javascript 为什么调用stroke会导致在HTML画布上绘制此元素?,javascript,html,canvas,fill,stroke,Javascript,Html,Canvas,Fill,Stroke,我正在一堆蓝色的圆圈上面画一个白色的长方形。这是填充圆的代码: 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
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]);
}
}
}
当我第一次调用draw()
然后调用winMessage()
时,白色矩形有一个圆圈的轮廓显示出来(见图)。我不知道为什么中风队列没有被清除。请使用我提供的信息更仔细地了解问题
您绘制的最后一个圆仍然保存在画布上下文中,当您调用
ctx.stroke()
时,它将被重新绘制。要清除它,需要在绘制矩形之前添加一个ctx.beginPath()
或者,您可以使用ctx.strokect()
,并跳过ctx.stroke()
更新的fiddle:很好的选择-以前没有想过使用它。谢谢
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);
}