簡體   English   中英

HTML5單擊按鈕后一切都消失了

[英]HTML5 Everything disappears after clicking a button

我是html5的新手。 我不確定這里發生了什么,我試圖做到這一點,所以每當單擊按鈕時,畫布上就會出現二次函數。 但是在我寫的內容中,每當我單擊按鈕時,在實際繪制所需的曲線后,所有內容都會消失。 這是代碼jsfiddle

<!DOCTYPE html>

<body>
<form action="">
a: <input type="text" name="tbax2" id="itbax2" value=0.01 size="4">
b: <input type="text" name="tbbx" id="itbbx" value=1 size="4">
c: <input type="text" name="tbc" id="itbc" value=40 size="4">
<button onclick="dibujarCurva()">Graficar</button>

</form>

<canvas id="myCanvas" width="500" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function dibujarCurva(){
 var ax2 = parseFloat(document.getElementById('itbax2').value);
 var bx = parseFloat(document.getElementById('itbbx').value);
 var c = parseFloat(document.getElementById('itbc').value);
 ctx.beginPath();
 ctx.strokeStyle = '#FF0000'
 x=0
 ctx.moveTo(0,150-(ax2*(x-250)*(x-250) + bx*(x-250) + c));
 while (x<501){
  ctx.lineTo(x,150-(ax2*(x-250)*(x-250) + bx*(x-250) + c));
  x=x+10
  ctx.stroke();}
  ctx.closePath();
 }
function dibujarGrid(){
 ctx.beginPath();
 ctx.strokeStyle = '#F2F2F2'
 ctx.moveTo(0,0);
 x=0
 while (x<501){
  ctx.moveTo(x,0);
  ctx.lineTo(x,300);
  x=x+10
  ctx.stroke();}
 x=0
 while (x<301){
  ctx.moveTo(0,x);
  ctx.lineTo(500,x);
  x=x+10
  ctx.stroke();}
 ctx.closePath();
 ctx.beginPath();
 ctx.strokeStyle = '#000000'
 ctx.moveTo(250,0);
 ctx.lineTo(250,300);
 ctx.stroke();
 ctx.moveTo(0,150);
 ctx.lineTo(500,150);
 ctx.stroke();
 }
 dibujarGrid()
 ctx.fillText(("ax^2 + bx + c"),10,20);
</script>

</body>

似乎正在嘗試提交表單。 一種快速簡便的解決方法是按以下方式更改onclick:

<button onclick="return dibujarCurva()">Graficar</button>

並添加一個

return false;

到dibujarCurva()函數的末尾。

如果您想有條件地提交,這很有用。 但是,正如slicedtoad和acontell指出的那樣,以下內容也可以在不對功能進行任何修改的情況下解決。

<button type="button" onclick="dibujarCurva()">Graficar</button>

您可以添加按鈕的type屬性,並阻止其發送表單:

<button type="button" onclick="dibujarCurva()">Graficar</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM