我正在尝试清理 Canvas 。我尝试关闭路径,但它没有改变任何东西。另外,我不太确定 ctxBg.close(); 是否有效是在正确的地方。
谢谢。
function drawGrid () {
drawGrid();
ctxBg.clearRect(0, 0, canvas.width, canvas.height);
function drawGrid () {
for (var i = 75; i <= canvasWidth-25; i+= 25) {
ctxBg.beginPath();
ctxBg.moveTo(-25 + i,55);
ctxBg.lineTo(-25 + i, canvasHeight - 55);
ctxBg.stroke();
}
for (var i = 25; i <= canvasHeight -75; i+= 25) {
ctxBg.beginPath();
ctxBg.moveTo(55,25 + i);
ctxBg.lineTo(canvasWidth-55, 25 + i);
ctxBg.stroke();
}ctxBg.close();
}
最佳答案
您有两个 drawGrid()
函数的定义:
function drawGrid () {
...
function drawGrid () {
你只能拥有一个。接下来,上下文中没有 close()
方法,只有 closePath()
。然而,这在这里没有用。 closePath 不会“结束”路径,而是连接路径中的第一个点和最后一个点,以便路径形状闭合。
当然,这对于线条来说没有用,并且无论如何,它必须在中风()之前调用。
第三,您正在(尝试)渲染网格,然后立即清除它。这不会在 Canvas 上显示任何内容。您需要将这些操作分开。
这是一个建议的解决方案。两个函数,一个绘制网格,一个清除网格:
var canvas = document.querySelector("canvas"),
canvasWidth = canvas.width, canvasHeight = canvas.height,
ctxBg = canvas.getContext("2d");
ctxBg.translate(0.5, 0.5); // just to make the lines sharper
function drawGrid() {
ctxBg.beginPath(); // this can be placed here
for (var i = 75; i <= canvasWidth - 25; i += 25) {
ctxBg.moveTo(-25 + i, 55);
ctxBg.lineTo(-25 + i, canvasHeight - 55);
}
for (var i = 25; i <= canvasHeight - 75; i += 25) {
ctxBg.moveTo(55, 25 + i);
ctxBg.lineTo(canvasWidth - 55, 25 + i);
}
ctxBg.stroke(); // stroke all at once
// remove button code (ref. comments)
var button = document.querySelector("button");
button.parentNode.removeChild(button);
}
function clearGrid() {
ctxBg.clearRect(0, 0, canvas.width, canvas.height);
}
<button onclick="drawGrid()">Grid</button>
<button onclick="clearGrid()">Clear</button><br>
<canvas></canvas>
更新:如果需要删除的按钮是 HTML 按钮(如上例所示),则可以使用以下样式将其删除:
// assumes the button element is stored in variable button:
button.style.display = "none";
或者完全使用它的parentNode
和removeChild()
:
button.parentNode.removeChild(button);
关于javascript - 清除 Canvas JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321259/