javascript - 为什么调用 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更仔细地查看问题。
解决方案
您绘制的最后一个圆圈仍然由画布上下文保存,并且在您调用ctx.stroke()
. 要清除它,您需要ctx.beginPath()
在绘制矩形之前添加一个。
或者,您可以ctx.strokeRect()
改用,然后跳过ctx.stroke()
.
推荐阅读
- go - 如何获取 gRPC 响应限制
- mongodb - 指定数据库名称时无法连接到 MongoDB
- android - Android Java Dagger Inject Problems
- reactjs - Material UI DateRange Picker --> DateTimeRange Picker?
- java - Java中逗号后只保留2位小数
- c++ - vscode, mingw, g++, 头文件包括从子目录失败
- python - 发送机器人也可以访问的频道
- flutter - Flutter:如何在流外访问数据和 NotifyListener
- python - AWS API 网关 + SQS + Lambda + 从 Lambda 获取响应到 API
- html - Bootstrap 5 - justifty-content-end 不工作