HTML5 点击按钮后,一切都会消失

HTML5 Everything disappears after clicking a button

本文关键字:消失 按钮 HTML5      更新时间:2023-09-26

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

似乎正在尝试提交表单。一个快速简便的解决方法是更改您的点击,如下所示:

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

并添加一个

return false;

到 dibujarCurva() 函数的末尾。

如果要有条件地提交,这将非常有用。然而,正如切片蟾蜍和acontell指出的那样,以下内容也可以在不对函数进行任何修改的情况下解决它。

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

您可以添加按钮的 type 属性并阻止它发送表单:

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