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