2016-05-17 16 views
0

ボタンを押すと、キャンバスの2番目のレイヤーに四角形が描画され、そのまま残ります。図面は機能し、滞在はしません。矩形は瞬時に現れますが、直ちに再び消えてしまい、その理由を理解できません。私はイベントリスナーをマウス操作に頼る四角形はフォームページがリロードさせ、提出されたようだ...HTMLキャンバスは描画直後に矩形を消去します

<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> 

答えて

1

あなたのコードをすべて<form>に入れたからです。フォームのボタンを押すとそれが送信され、ページから離れて移動します。

<form>(必要でないと思われます)を削除するか、送信をキャンセルするにはdraw2機能を変更する必要があります。

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

それとも、直接フォームにonsubmitハンドラをアタッチし、そこにそれを取り消すことができます。

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

ありがとう!私は実際にここで簡潔さのために剥ぎ取られたもののためのフォームが必要です。あなたの提案はそのトリックをするようです。 –

2

とどまります。この行を交換してみてください:

これで
<form action="" id="inputTactics"> 

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

編集:この質問は、関連すると思われる - Want html form submit to do nothing

0

私はあなたが提出するトリガされ、formタグを持っているからだと思います。

フォームタグを削除すると機能します。

1

あなたの問題はフォームタグであり、ボタンをクリックするとフォームが送信されます。

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>

関連する問題