Skip to main content

Canvas

The Canvas class simplifies working with an HTML5 Canvas element and its 2D rendering context.

Overview

This class provides a streamlined approach to handling a canvas by:

  • Automatically creating the <canvas> element.
  • Managing resizing based on viewport or container size.
  • Offering access to useful properties like width, height, dpr, and context.
  • Supporting both automatic and manual resizing.
  • Implementing conditional rendering to prevent errors when the canvas is invisible or has zero size.

Example

Explore a live example in CodeSandbox:

Props

Static Props

Static properties are set during initialization and cannot be modified later.

NameDescriptionTypeDefault Value
containerParent element used to determine canvas size. If null, it uses the viewport.HTMLElement | nullnull
appendIf true, appends the canvas to the container. Ignored if container is null.booleantrue
resizeOnInitAutomatically adjusts canvas size on initialization.booleantrue
resizeOnRuntimeEnables dynamic resizing based on viewport or container changes.booleanfalse
viewportTargetDefines which dimension(s) should trigger a resize. Learn more'width' | 'height' | 'both' | 'width_' | 'height_' | 'any''any'
resizeDebounceDebounce time (ms) for resize handling.number0

Mutable Props

Mutable properties can be updated at runtime using .updateProps().

NameDescriptionTypeDefault Value
widthCanvas width. Use 'auto' to match the container's width.'auto' | number'auto'
heightCanvas height. Use 'auto' to match the container's height.'auto' | number'auto'
dprDevice Pixel Ratio (DPR). Use 'auto' for automatic detection.'auto' | number'auto'

Accessors

note

All Module's accessors are available in this class.

canRender

Type: boolean

Checks if the canvas is ready to render.

canvas

Type: HTMLCanvasElement

The canvas element instance.

ctx

Type: CanvasRenderingContext2D

The 2D rendering context.

dpr

Type: number

Current device pixel ratio.

height

Type: number

Canvas height (DPR applied).

offsetHeight

Type: number

Height without DPR scaling.

offsetWidth

Type: number

Width without DPR scaling.

width

Type: number

Canvas width (DPR applied).

Methods

note

All Module's methods are available in this class.

render

Renders content on the canvas if it's ready.

instance.render(({ canvas, ctx, dpr, width, height }) => {
// Draw your scene here
});

resize

Triggers a canvas resize based on container or viewport dimensions.

instance.resize();

updateProps

Updates instance properties.

instance.updateProps({
width: 100,
height: 100,
});

destroy

Destroys the instance and cleans up resources.

instance.destroy();

Callbacks

note

All Module's callbacks are available in this class.

resize

Fires when the canvas is resized.

const destruct = instance.on('resize', () => console.log('Canvas resized'));

// Cancel the callback
destruct();