Touch Pressure Drawing Demo

Drawing on a canvas with touch pressure support (try it with a Surface, Wacom tablet, or iPad).

by Ian Sanders

HTML

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

CSS

#canvas {
  border: 1px solid black;
  touch-action: none;
}

JavaScript

class DrawingApp {
	constructor(id) {
  	this.canvas = document.getElementById(id);
    this.context = canvas.getContext("2d");
    this.canvas.addEventListener("pointerdown", this.startDrawing.bind(this));
    this.canvas.addEventListener("pointerup", this.stopDrawing.bind(this));
    this.previousPosition = {
    	x: 0, y: 0
    };
    this.draw = this.draw.bind(this);
  }
  
  draw(event) {
  	const position = {x: event.offsetX, y: event.offsetY};
  	this.drawLine(
    	this.previousPosition,
      position,
      10*event.pressure
     )
     this.previousPosition = position;
  }
  
  startDrawing(event) {
  	this.canvas.addEventListener("pointermove", this.draw);
    this.canvas.setPointerCapture(event.pointerId);
    this.previousPosition = {
    	x: event.offsetX, y: event.offsetY
    }
  }
  
  stopDrawing() { 
  	this.canvas.removeEventListener("pointermove", this.draw);
    this.canvas.releasePointerCapture(event.pointerId);
  }
  
  drawLine(from, to, thickness) {
  	this.context.beginPath();
  	this.context.strokeStyle = 'black';
  	this.context.lineWidth = thickness;
  	this.context.moveTo(from.x, from.y);
  	this.context.lineTo(to.x, to.y);
  	this.context.stroke();
  	this.context.closePath();
  }
}

document.addEventListener("DOMContentLoaded", () => {
	new DrawingApp("canvas");
});