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
, andcontext
. - 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 CodePen:
Props
Static Props
Static properties are set during initialization and cannot be modified later.
container
- Type:
HTMLElement | null
- Default:
null
- Parent element used to determine canvas size. If
null
, it uses the viewport.
append
- Type:
boolean
- Default:
true
- If
true
, appends the canvas to thecontainer
. Ignored ifcontainer
isnull
.
resizeOnInit
- Type:
boolean
- Default:
true
- Automatically adjusts canvas size on initialization.
resizeOnRuntime
- Type:
boolean
- Default:
false
- Enables dynamic resizing based on viewport or container changes.
viewportTarget
- Type:
'width' | 'height' | 'both' | 'onlyWidth' | 'onlyHeight' | 'any' | 'trigger'
- Default:
'any'
- Defines which dimension(s) should trigger a resize. Learn more
resizeDebounce
- Type:
number
- Default:
0
- Debounce time (ms) for resize handling.
Mutable Props
Mutable properties can be updated at runtime using .updateProps()
.
width
- Type:
'auto' | number
- Default:
'auto'
- Canvas width. Use
'auto'
to match the container's width.
height
- Type:
'auto' | number
- Default:
'auto'
- Canvas height. Use
'auto'
to match the container's height.
dpr
- Type:
'auto' | number
- Default:
'auto'
- Device Pixel Ratio (DPR). Use
'auto'
for automatic detection.
Accessors
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
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
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();