HLJ 发布于
2018-08-20 17:11:31

HTML5 Canvas clearRect()方法清除画布

要清除HTML5 Canvas,我们可以使用clearRect()方法清除画布位图。 这比清除画布的其他技术要好得多,例如重置画布宽度和高度,或者破坏canvas元素然后重新创建它。
说明:单击清除按钮以清除画布
html代码:
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #buttons {
        position: absolute;
        top: 5px;
        left: 10px;
      }
      #buttons > input {
        padding: 10px;
        display: block;
        margin-top: 5px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <div id="buttons">
      <input type="button" id="clear" value="Clear">
    </div>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      // begin custom shape
      context.beginPath();
      context.moveTo(170, 80);
      context.bezierCurveTo(130, 100, 130, 150, 230, 150);
      context.bezierCurveTo(250, 180, 320, 180, 340, 150);
      context.bezierCurveTo(420, 150, 420, 120, 390, 100);
      context.bezierCurveTo(430, 40, 370, 30, 340, 50);
      context.bezierCurveTo(320, 5, 250, 20, 250, 50);
      context.bezierCurveTo(200, 5, 150, 20, 170, 80);

      // complete custom shape
      context.closePath();
      context.lineWidth = 5;
      context.strokeStyle = 'blue';
      context.stroke();

      // bind event handler to clear button
      document.getElementById('clear').addEventListener('click', function() {
        context.clearRect(0, 0, canvas.width, canvas.height);
      }, false);

    </script>
  </body>
</html>

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2018-08-20/178.html
最后生成于 2023-06-18 18:38:18
此内容有帮助 ?
0