[英]HTML Canvas erases rectangle right after drawing
按下按鈕后,應該在我的畫布的第二層上繪制一個矩形,並且該矩形應該停留在該位置。 繪圖有效,停留無效。 矩形會立即顯示,但立即會再次消失,我不知道為什么。 我使用事件偵聽器在鼠標動作上繪制的矩形保持不變...
<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>
我認為這是因為您有一個觸發提交的表單標簽。
帶走表單標簽,它將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.