Draw with the Mouse on the Canvas using JavaScript

Below is a simple example of drawing with the mouse on an HTML5 Canvas element in the browser using JavaScript.

The example uses Vanilla JavaScript and HTML5.

Overall, the code sets up event handler functions for the mouse button being held down, released, and while the mouse is being moved.

The flag isDrawing controls whether a line is drawn to the target point (targetX, targetY).

The flag is turned on when the mouse is held down, and turned off when the mouse is released.

Note that the coordinates of points start at the top left of the canvas, and grow down and to the right.

The coordinates of the current mouse pointer position are passed into the event handlers as e.pageX and e.pageY.

The page coordinates are relative to the entire page, so there is an offset to the canvas element’s top left. Therefore, to get the correct final drawing coordinates, we use:

targetX = e.pageX - canvas.offsetLeft;
targetY = e.pageY - canvas.offsetTop;

The canvas functions beginPath() and closePath() start and stop the drawing path.
The path is opened on mouse down, and closed on mouse up.
The actual drawing is executed with the canvas method stroke().

The HTML file and JavaScript file are below.

draw-on-canvas.html
<html>

  <head>
    <title>Draw on the Canvas</title>
    <script src="draw-on-canvas.js" type="module">
    </script>
  </head>

  <body>
    <canvas id="myCanvas" width="500" height="500">
    </canvas>
  </body>

</html>
draw-on-canvas.js
// State variables.
let canvas = null;
let context = null; // Drawing context.
let isDrawing = false;

// Set canvas context, attach event handlers.
window.onload = function() {
  canvas = document.getElementById("myCanvas");
  context = canvas.getContext("2d");

  isDrawing = false;

  canvas.addEventListener("mousedown", startDrawing);
  canvas.addEventListener("mouseup", stopDrawing);
  canvas.addEventListener("mousemove", draw);
}

// Mouse down: enter drawing state.
const startDrawing = function(e) {
  isDrawing = true;

  // Coordinates within canvas.
  let targetX = e.pageX - canvas.offsetLeft;
  let targetY = e.pageY - canvas.offsetTop;

  // Start a new drawing path and move pen there.
  context.beginPath();
  context.moveTo(targetX, targetY);
}

// Mouse up: exit drawing state.
const stopDrawing = function(e) {
  isDrawing = false;
  context.closePath();
}

// Mouse move: continuous drawing when flag on.
const draw = function(e) {
  if (isDrawing) {
    let targetX = e.pageX - canvas.offsetLeft;
    let targetY = e.pageY - canvas.offsetTop;
    context.lineTo(targetX, targetY);
    context.stroke(); // Draw line.
  }
}