gengns ES

An entry from the gengns log, written by Génesis García Morilla · · CSS3, HTML5, JavaScript

Freehand Drawing in HTML5 Canvas

We are gonna use PointerEvents that are hardware agnostic (mouse, pen, touch, etc) to draw lines in an HTML Canvas.

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
}

HTML

<canvas></canvas>

CSS

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

Tags: canvas