Skip to main content

Canvas Wrapper

Canvas is the ergonomic entry point. It accepts either a canvas element or a query selector, creates a Brush, configures the canvas for the current device pixel ratio or an explicit document size, and binds pointer events.

Canvas wrapper live demo

The Canvas wrapper wires pointer events, pressure simulation, and device scaling automatically.

Loading demo…
import { Canvas } from "fuderu";

const painter = new Canvas({
canvas: document.querySelector("canvas")!,
document: {
width: 1024,
height: 768,
},
pressureSimulation: true,
brush: {
color: "#222222",
size: 18,
roundness: 0.8,
},
});

Document Size

The visible canvas size comes from CSS. The drawing buffer comes from document.width and document.height, or from the element's CSS size multiplied by window.devicePixelRatio when document is omitted.

const painter = new Canvas({
canvas: "#paint",
document: {
width: 1536,
height: 1536,
},
});

Call resize() after changing the element's visible size:

painter.resize();

Call setDocumentSize() to change the logical artwork size. This clears the canvas and resets undo history.

painter.setDocumentSize(2048, 2048);

Pressure

Real pen pressure is used when the pointer is a pen and event.pressure is available. Mouse and touch input can use simulated pressure:

const painter = new Canvas({
canvas: "#paint",
pressureSimulation: true,
});

Set pressureSimulation to false to use a flat pressure of 1 for mouse and touch input.

lastPressure stores the most recent pressure sent to the brush, which is handy for UI meters without advancing the pressure simulator again.

Access The Brush

The wrapper exposes the underlying brush:

painter.brush.blendMode = "multiply";
painter.brush.filter = "blur(0.2px)";
painter.brush.maxUndoRedoStackSize = 20;

Use this when the high-level wrapper is still useful, but you need a lower-level brush feature.