HTML5 Game - Drawing on a Canvas with the Mouse

Description

Drawing on a Canvas with the Mouse

Demo

ResultView the demo in separate window

<!DOCTYPE html> 
<html> 
    <head> 
        <title>Canvas Demo</title> 
        <style> 
canvas { /*from  w  ww  . ja  va 2 s .  c o m*/
  border: 1px solid #000; 
  cursor: crosshair; 
} 
        </style> 
    </head> 
    <body> 
      <canvas id="myCanvas" width="500" height="500">Did You Know: Every time 
        you use a browser that doesn't support HTML5
      </canvas> 
      <script> 
// Get the context we will be using for drawing. 
let myCanvas = document.getElementById('myCanvas'); 
let myContext = myCanvas.getContext('2d'); 
myContext.strokeStyle = '#000'; 
  
// Whether or not the mouse button is being pressed. 
let isMouseDown = false; 
  
// Add a mousedown event listener that will set the isMouseDown flag to true, 
// and move the pen to the new starting location. 
myCanvas.addEventListener('mousedown', function(event) { 
  myContext.moveTo(event.clientX, event.clientY); 
  isMouseDown = true; 
}, false); 
  
// Add a mouseup event handler that will set the isMouseDown flag to false. 
myCanvas.addEventListener('mouseup', function(event) { 
  isMouseDown = false; 
}, false); 
  
// Add a mousemove event handler that will draw a line to the current mouse 
// coordinates.  
myCanvas.addEventListener('mousemove', function(event) { 
  if (isMouseDown) { 
    window.requestAnimationFrame(function() { 
      myContext.lineTo(event.clientX, event.clientY); 
      myContext.stroke(); 
    }); 
  } 
}, false); 
      </script> 
    </body> 
</html>

Related Topic