Freehand Drawing in HTML5 Canvas

by Génesis García Morilla

HTML

<canvas></canvas>

CSS

body {
  margin: 0;
  padding: 0;
  background-color: #bbb;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

JavaScript

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

// Same window dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// We need to track mouse/finger position and down/up
let x, y, down // we could set this variables inside the canvas obj (as you wish)

// Start
canvas.onpointerdown = e => {
  const { pageX, pageY } = e
  down = true
  x = pageX
  y = pageY
}

// End
canvas.onpointerup = () => down = false

// Move
canvas.onpointermove = canvas.ontouchmove = e => {
  // Return if we haven't finish yet
  if (!down) return
  const { pageX, pageY } = (e.touches && e.touches[0]) || e
  // Draw line
  ctx.beginPath()
  ctx.moveTo(x, y)
  ctx.lineTo(pageX, pageY)
  ctx.lineWidth = 2
  ctx.stroke()
  // Update
  x = pageX
  y = pageY
}