HTML Canvas Mouse Event Draw with mouse

Description

HTML Canvas Mouse Event Draw with mouse

View in separate window

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Drawing App</title>
  </head>/* w ww . j a v a2s .c  o  m*/
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Click and draw with the mouse.</aside>
    <script>
captureMouse = function (element) {
  var mouse = {x: 0, y: 0, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;
  
  element.addEventListener('mousemove', function (event) {
    var x, y;
    
    if (event.pageX || event.pageY) {
      x = event.pageX;
      y = event.pageY;
    } else {
      x = event.clientX + body_scrollLeft + element_scrollLeft;
      y = event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    mouse.x = x;
    mouse.y = y;
    mouse.event = event;
  }, false);
  
  return mouse;
}; 
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          mouse = captureMouse(canvas);

      canvas.addEventListener('mousedown', function () {
        context.beginPath();
        context.moveTo(mouse.x, mouse.y);
        canvas.addEventListener('mousemove', onMouseMove, false);
      }, false);

      canvas.addEventListener('mouseup', function () {
        canvas.removeEventListener('mousemove', onMouseMove, false);
      }, false);

      function onMouseMove () {
        context.lineTo(mouse.x, mouse.y);
        context.stroke();
      }
    };
    </script>
  </body>
</html>



PreviousNext

Related