Canvas How to - Track Canvas Mouse Trail








Question

We would like to know how to track Canvas Mouse Trail.

Answer


<!-- w  w w.java 2  s .  c  om-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
canvas { border: 1px solid #ccc }
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var el = document.getElementById('c');
    var ctx = el.getContext('2d');
    var isDrawing;
    el.onmousedown = function(e) {
      isDrawing = true;
      ctx.moveTo(e.clientX, e.clientY);
    };
    el.onmousemove = function(e) {
      if (isDrawing) {
        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
      }
    };
    el.onmouseup = function() {
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      isDrawing = false;
    };
}//]]>  
</script>
</head>
<body>
  <canvas id="c" width="500" height="300"></canvas>
</body>
</html>

The code above is rendered as follows: