HTML画布在绘图后立即擦除矩形

HTML Canvas erases rectangle right after drawing

本文关键字:擦除 绘图 HTML      更新时间:2023-09-26

按下按钮后,应该在画布的第二层绘制一个矩形,并且它应该保持在那里。画画行,留宿不行。矩形出现了一瞬间,但立即又消失了,我不明白为什么。我用鼠标动作和事件监听器绘制的矩形保持不变。。。

<html>
<body>

<h2>Raumaufteilung a: </h2>
<form action="" id="inputTactics"> 
<table border="1">
<tr><td><button id="Butt0" onclick="draw2()">Alle</button></td>
    <td  width="600" height="400"  valign="top"> 
        <div id="TacticsPic">  
          <canvas id="ground" width="525" height="340"
                style="border:2px solid #ffffff; background-color: #23D419; position: absolute; z-index: 0">
          </canvas>
          <canvas id="c2" width="525" height="340"
                style="position: absolute; z-index: 1">
          </canvas>
          <canvas id="c3" width="525" height="340"
                style="position: absolute; z-index: 2">
          </canvas>
            <br>
        </div>
    </td>
    </tr>  
</table>  
</form>   

<script>
    var canvasTac = document.querySelector("#c2");
    var ctxTac = canvasTac.getContext('2d');

function draw2() {
    ctxTac.strokeRect(100,100,250,100);
};
</script>
</body>
</html>

表单似乎正在提交,导致页面重新加载。尝试替换此行:

<form action="" id="inputTactics"> 

这个:

<form onsubmit="return false;" id="inputTactics"> 

编辑:这个问题似乎很相关-希望html表单提交不做任何事情

这是因为您已经将所有代码放在了<form>中。按下表单中的按钮提交表单,您将离开页面。

要么删除<form>(看起来不需要它),要么需要修改draw2函数来取消提交。

function draw2() {
  ctxTac.strokeRect(100, 100, 250, 100);
  event.preventDefault();
}

或者,您可以将onsubmit处理程序直接附加到表单并在那里取消它。

<form action="" id="inputTactics" onsubmit="return false;"> 

您的问题是表单标签,如果您单击按钮,它将提交表单。

var canvasTac = document.querySelector("#c2");
var ctxTac = canvasTac.getContext('2d');
function draw2() {
  ctxTac.strokeRect(100, 100, 250, 100);
};
document.getElementById("Butt0").addEventListener("click", draw2);
<h2>Raumaufteilung a: </h2>
<table border="1">
  <tr>
    <td>
      <button id="Butt0">Alle</button>
    </td>
    <td width="600" height="400" valign="top">
      <div id="TacticsPic">
        <canvas id="ground" width="525" height="340" style="border:2px solid #ffffff; background-color: #23D419; position: absolute; z-index: 0">
        </canvas>
        <canvas id="c2" width="525" height="340" style="position: absolute; z-index: 1">
        </canvas>
        <canvas id="c3" width="525" height="340" style="position: absolute; z-index: 2">
        </canvas>
        <br>
      </div>
    </td>
  </tr>
</table>

我认为这是因为您有一个触发提交的表单标记。

去掉表单标签,它就会起作用。