Skip to content
jshacks.dev
Browser

Build a Drawing App With Canvas in Vanilla JavaScript

Build a drawing app with canvas in vanilla JavaScript using pointer events, smooth strokes, brush and color, an eraser, undo, high-DPI scaling and PNG export.

8 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Google Chrome and Redis logos.

A drawing app is one of the most rewarding canvas projects, because you see the result of every line of code immediately. The basic idea is short: listen for the pointer, and draw a line from the last position to the new one. The details are where the quality lives: strokes that look smooth instead of jagged, a canvas that is sharp on high-density screens, support for mouse, touch and stylus with one set of handlers, an undo that works, and a way to save the picture. This post builds a drawing app with canvas in vanilla JavaScript step by step. It uses pointer events so one code path serves every input device, stores strokes as data so undo is trivial, smooths the line with quadratic curves, scales for devicePixelRatio and exports the drawing as a PNG. The canvas API is documented on MDN and pointer events in the W3C specification.

The page

A canvas, a toolbar and a few controls. The canvas needs touch-action: none, or the browser will scroll the page when you draw with a finger.

index.htmlHTML
<main>
  <h1>Sketch</h1>
  <div class="tools" role="toolbar" aria-label="Drawing tools">
    <label>Color <input type="color" id="color" value="#1e1e1e"></label>
    <label>Size <input type="range" id="size" min="1" max="40" value="6"></label>
    <button type="button" id="pen" aria-pressed="true">Pen</button>
    <button type="button" id="eraser" aria-pressed="false">Eraser</button>
    <button type="button" id="undo">Undo</button>
    <button type="button" id="clear">Clear</button>
    <button type="button" id="save">Save PNG</button>
  </div>
  <canvas id="board" width="800" height="500" aria-label="Drawing area" role="img"></canvas>
</main>
<script type="module" src="draw.js"></script>
draw.cssCSS
#board {
  display: block;
  width: 100%;
  max-width: 800px;
  aspect-ratio: 16 / 10;
  border: 1px solid #999;
  background: #fff;
  touch-action: none;
  cursor: crosshair;
}
Text
(a white drawing area with a toolbar above it)

The canvas is a bitmap, and a screen reader cannot read it, so the label tells assistive technology what it is. A drawing surface is inherently visual, and the honest accessible alternative is to offer the export and describe the tool, rather than to pretend the canvas has content.

Sharp on every screen

A canvas has two sizes: the pixel grid you set with its width and height attributes, and the size it is displayed at with CSS. On a high-density display, a canvas whose grid matches its CSS size looks blurry because each canvas pixel stretches over several physical pixels. Scale the grid by devicePixelRatio and scale the drawing context back so you can keep drawing in CSS pixels.

setup.jsJavaScript
const canvas = document.querySelector("#board");
const ctx = canvas.getContext("2d");

function resize() {
  const ratio = window.devicePixelRatio || 1;
  const { width, height } = canvas.getBoundingClientRect();
  canvas.width = Math.round(width * ratio);
  canvas.height = Math.round(height * ratio);
  ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  redraw();
}

window.addEventListener("resize", resize);
console.log(typeof resize);
Text
function

Changing canvas.width or height clears the canvas and resets the context state, which is why the function re-applies the transform and the line settings and then calls redraw(), defined below, to paint the saved strokes again. That is one more reason to keep the strokes as data.

Strokes as data

Instead of drawing and forgetting, record each stroke as an object with a color, a size, a mode and a list of points. Drawing is then a pure function of that list, which makes undo, redraw after resize and export all straightforward.

strokes.jsJavaScript
const strokes = [];
let current = null;

export function startStroke(point, { color, size, erase }) {
  current = { color, size, erase, points: [point] };
  strokes.push(current);
  return current;
}

export function extendStroke(point) {
  if (current) current.points.push(point);
}

export function endStroke() {
  current = null;
}

export function undo() {
  strokes.pop();
}

export function clearAll() {
  strokes.length = 0;
}

export function all() {
  return strokes;
}

startStroke({ x: 1, y: 1 }, { color: "#000", size: 4, erase: false });
extendStroke({ x: 5, y: 5 });
endStroke();
console.log(all().length, all()[0].points.length);
undo();
console.log(all().length);
Text
1 2
0

Undo is one line, removing the last stroke, and redrawing produces the picture without it. Keeping the strokes in memory also lets you save a drawing as JSON and reopen it later, which a bare bitmap does not allow.

Smooth lines

Connecting recorded points with straight segments looks jagged, especially when the pointer moves fast and the events are far apart. A well-known trick is to draw quadratic curves through the midpoints of consecutive points, using each real point as the control point.

paint.jsJavaScript
import { all } from "./strokes.js";

function drawStroke(stroke) {
  const { points, size, color, erase } = stroke;
  ctx.save();
  ctx.globalCompositeOperation = erase ? "destination-out" : "source-over";
  ctx.strokeStyle = color;
  ctx.fillStyle = color;
  ctx.lineWidth = size;

  if (points.length === 1) {
    ctx.beginPath();
    ctx.arc(points[0].x, points[0].y, size / 2, 0, Math.PI * 2);
    ctx.fill();
  } else {
    ctx.beginPath();
    ctx.moveTo(points[0].x, points[0].y);
    for (let i = 1; i < points.length - 1; i++) {
      const midX = (points[i].x + points[i + 1].x) / 2;
      const midY = (points[i].y + points[i + 1].y) / 2;
      ctx.quadraticCurveTo(points[i].x, points[i].y, midX, midY);
    }
    const last = points[points.length - 1];
    ctx.lineTo(last.x, last.y);
    ctx.stroke();
  }
  ctx.restore();
}

export function redraw() {
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
  all().forEach(drawStroke);
}

console.log(typeof redraw);
Text
function

A single click has one point, which would draw nothing with a line, so the code draws a filled circle instead. The eraser uses the destination-out composite operation, which removes pixels instead of painting, and since erasing is just another stroke in the list, undo works for it too. Note that an eraser stroke affects everything drawn before it in the list, which is what you want.

Pointer events

Pointer events unify mouse, touch and pen. When a drawing begins, call setPointerCapture, so the canvas keeps receiving events even if the pointer leaves it before the button is released.

pointer.jsJavaScript
import { startStroke, extendStroke, endStroke } from "./strokes.js";

const tool = { color: "#1e1e1e", size: 6, erase: false };
let drawing = false;

function position(event) {
  const rect = canvas.getBoundingClientRect();
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}

canvas.addEventListener("pointerdown", (event) => {
  if (event.button !== 0 && event.pointerType === "mouse") return;
  canvas.setPointerCapture(event.pointerId);
  drawing = true;
  startStroke(position(event), tool);
  redraw();
});

canvas.addEventListener("pointermove", (event) => {
  if (!drawing) return;
  const events = event.getCoalescedEvents?.() ?? [event];
  for (const e of events) extendStroke(position(e));
  redraw();
});

function stop(event) {
  if (!drawing) return;
  drawing = false;
  endStroke();
  canvas.releasePointerCapture?.(event.pointerId);
}

canvas.addEventListener("pointerup", stop);
canvas.addEventListener("pointercancel", stop);
Text
(pressing and dragging draws a smooth line that follows the mouse, finger or pen)

getCoalescedEvents() returns the extra pointer positions the browser merged into one event, which gives smoother lines on fast movement and is supported in current browsers, so the code falls back to the single event where it is missing. Redrawing everything on each move is fine for modest drawings; for thousands of strokes, draw the new segment incrementally on the visible canvas and do a full redraw only for undo and resize.

Controls

The controls change the tool object, and Undo and Clear update the list and redraw.

controls.jsJavaScript
import { undo, clearAll } from "./strokes.js";

document.querySelector("#color").addEventListener("input", (e) => { tool.color = e.target.value; });
document.querySelector("#size").addEventListener("input", (e) => { tool.size = Number(e.target.value); });

function setTool(erase) {
  tool.erase = erase;
  document.querySelector("#pen").setAttribute("aria-pressed", String(!erase));
  document.querySelector("#eraser").setAttribute("aria-pressed", String(erase));
}

document.querySelector("#pen").addEventListener("click", () => setTool(false));
document.querySelector("#eraser").addEventListener("click", () => setTool(true));
document.querySelector("#undo").addEventListener("click", () => { undo(); redraw(); });
document.querySelector("#clear").addEventListener("click", () => { clearAll(); redraw(); });

document.addEventListener("keydown", (event) => {
  if ((event.ctrlKey || event.metaKey) && event.key === "z") {
    event.preventDefault();
    undo();
    redraw();
  }
});

resize();
console.log(tool.size);
Text
6

Save the picture

canvas.toBlob() produces a PNG file you can download through a temporary link. A transparent canvas exports with a transparent background, so paint white behind the strokes first if you want a white page.

save.jsJavaScript
document.querySelector("#save").addEventListener("click", () => {
  const out = document.createElement("canvas");
  out.width = canvas.width;
  out.height = canvas.height;
  const octx = out.getContext("2d");
  octx.fillStyle = "#ffffff";
  octx.fillRect(0, 0, out.width, out.height);
  octx.drawImage(canvas, 0, 0);

  out.toBlob((blob) => {
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "sketch.png";
    link.click();
    URL.revokeObjectURL(url);
  }, "image/png");
});
Text
(clicking Save downloads sketch.png at the full device resolution on a white background)

Revoking the object URL after the click frees the memory the browser held for the blob.

Practical notes

Check the touch behavior on a real phone: if the page scrolls while you draw, touch-action: none is missing. Test the stylus: event.pressure ranges from 0 to 1, and you can multiply it into the line width for a natural feel, though a mouse reports a constant 0.5 when a button is down. Handle the case where the window is resized while a stroke is active, which the redraw logic copes with because strokes are in CSS pixels. Save progress to localStorage as JSON, guarded with try and catch, and be aware that a very long drawing can exceed the storage limit, so catch the quota error. Finally, think about what a keyboard user can do: at least provide a Save button and an Undo that works without a pointer, since the drawing itself needs one.

Testing the drawing app

Draw slowly and quickly, and check that fast strokes remain smooth rather than turning into straight segments. Draw a single dot with a click and confirm that a dot appears. Switch to the eraser, rub over a line and confirm that it disappears, then press Undo and check that the line returns, since the eraser is itself a stroke. Resize the window while the picture is on screen and make sure nothing is lost or stretched, which proves the redraw from stored strokes works.

Test on a touch device and with a stylus if you have one. A finger should draw without scrolling the page, a second finger should not break the stroke of the first, and a palm resting on the screen is reported as another pointer, which you can ignore by tracking only the pointer id that started the stroke. Check the exported PNG by opening it: it should have the right resolution, a white background and the same picture. Finally, test with the browser zoomed in and on a high-density display to confirm the lines are sharp and the pointer position matches the line, which is where mistakes in the scaling code show up.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.