Canvas How to - Clear an area








Question

We would like to know how to clear an area.

Answer


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1202" height="602" style="border:1px solid #d3d3d3;"></canvas>
<script type='text/javascript'>
(function () {<!--from ww w  .j  a va  2  s .c  om-->
    'use strict';
    window.onload = function () {
      var canvas = document.getElementById("myCanvas");
      var ctx = canvas.getContext("2d");
      function reset() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath();
        ctx.moveTo(100, 150);
        ctx.lineTo(450, 50);
        ctx.stroke();
      }
      reset();
    };
})();
</script>
</body>
</html>

The code above is rendered as follows: