HTML5 Game - Draw with mouse

Description

Draw with mouse

Demo

ResultView the demo in separate window

<!doctype html>  
<html>  
 <head>  
     <style>canvas{border:1px solid red;}</style>
 </head>  /*from   ww  w .  ja v  a2s .c  om*/
 <body>  
  <canvas id="canvas" width="400" height="400"></canvas>  
  <script>  
  
  window.onload = function () {  
    let canvas = document.getElementById('canvas'),  
        context = canvas.getContext('2d'),  
        mouse = captureMouse(canvas);  
  
    function onMouseMove () {  
      context.lineTo(mouse.x, mouse.y);  
      context.stroke();  
    }  
    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 captureMouse(element) {
  let 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) {
    let 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;
}       
  </script>  
 </body>  
</html>

Related Topic