简体   繁体   English

清除按钮不适用于我的 javascript 和 hmtl5 画布

[英]Clear button not working with my javascript and hmtl5 canvas

I'am very new at this and I'm trying to create a signature drawing program in html, canvas and javascript.我对此很陌生,我正在尝试用 html、canvas 和 javascript 创建一个签名绘图程序。

Im trying to get the clear button working with this function;我试图让清除按钮使用此功能;

function clearCanvas() {
   var canvas = document.getElementById('canvas');
   var context = canvas.getContext('2d');
   context.clearRect(0, 0, canvas.width, canvas.height);

But it does not seem to work.但它似乎不起作用。 I don't really know where in the js script to put the function for it to be executed in the html code.我真的不知道在 js 脚本中的何处放置要在 html 代码中执行的函数。

this is the html code:这是 html 代码:

<!DOCTYPE html>
<html lang="sv">
  <head>
    <meta charset="utf-8">
    <script type="text/javascript" src="uppgift-6.js"></script>
    <title>Uppgift6</title>
    <style type="text/css">
      #canvas { position: relative; }
      #bildruta { border: 2px solid #000; }
      body {font-family: Calibri}
      h2 {font-size: 150%; color: BLACK; background-color: BEIGE; padding:  20px; margin: 5px auto; text-align: center;}
    </style>
  </head>
  <body>
    <h2>Signatur</h2>
    <div id="canvas">
      <canvas id="bildruta" width="600" height="400"></canvas>
    </div>
    <button type="button" onclick="clearCanvas()"> Clear signature </button>
  </body>
</html>

Grateful for all help that i can get!感谢我能得到的所有帮助!

Your ID is not correct.您的 ID 不正确。 Change your id or change the JS line like this:更改您的 id 或更改 JS 行,如下所示:

function clearCanvas() {
   var canvas = document.getElementById('bildruta'); // that's the correct ID
   var context = canvas.getContext('2d');
   context.clearRect(0, 0, canvas.width, canvas.height);
}

And it works.它有效。

var canvas = document.getElementById('canvas') points to this div <div id="canvas"> not to your canvas. var canvas = document.getElementById('canvas')指向这个 div <div id="canvas">而不是你的画布。 It should be document.getElementById('bildruta')它应该是document.getElementById('bildruta')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM