Skip to content
Igor Zinken edited this page Jan 20, 2024 · 22 revisions

Canvas

The core actor of the zCanvas library. Creating an instance of Canvas creates an HTMLCanvasElement that can be inserted into your document to render your graphics. The Canvas instance then acts as an API to interact with the HTML canvas, add Sprites, etc.

Each Canvas instance manages its own resources, meaning assets used for drawing, such as images.

constructor

Canvas( props: CanvasProps ) {}

Constructs a new Canvas-instance. The props argument is an Object that supports the following properties (all of which are optional):

interface CanvasProps {
    width?: number;
    height?: number;
    fps?: number;
    backgroundColor?: string;
    animate?: boolean;
    smoothing?: boolean;
    stretchToFit?: boolean;
    autoSize?: boolean;
    viewport?: Size;
    viewportHandler?: ({}: { type: "panned", value: Viewport }) => void;
    preventEventBubbling?: boolean;
    optimize?: "auto" | "worker" | "none";
    parentElement?: HTMLElement;
    onUpdate?: ( now: DOMHighResTimeStamp, framesSinceLastRender: number ) => void;
    onResize?: ( width: number, height: number ) => void;
    debug?: boolean;
}
  • width and height define the dimensions as numbers (defaults to 300 x 300 pixels)
  • fps defines the frame rate of the canvas, this will default to 60 and only applies when the Canvas animates
  • backgroundColor defines the background color of the canvas, by default this will be transparent (also see setBackgroundColor()). It is recommended to provide a background color when your Canvas will always have an opaque background (e.g. background image) as this provides a slight performance improvement.
  • animate is a boolean value that indicates whether the canvas will redraw its contents constantly (on every animation frame, when true) or require the user to invoke a render manually (using invalidate()). When creating visual content within the context of a animation/game loop you'd likely want this to be true
  • smoothing specifies whether or not to use smoothing (true by default, better for photos) or not (better for pixel art)
  • stretchToFit specifies whether or not the Canvas should stretch to fill the window (defaults to false). See stretchToFit()
  • autoSize specifies whether to automatically scale the Canvas when the window is resized / orientation changes, defaults to false
  • viewport is a Size object describing the optional viewport dimensions (see setViewport() or rendering large content within a fixed viewport)
  • viewportHandler is a Function which is invoked on certain state changes (e.g. viewport positioning) which can be used to sync the Canvas viewport state externally (for instance, to align scrollbars)
  • preventEventBubbling specifies whether the Canvas should prevent events to bubble down (defaults to false)
  • optimize specifies which rendering engine to use. When worker, the Worker is used (when available), when none rendering is done on the main thread. The default value is auto which will choose the best available option
  • parentElement is a DOM Element that be the container of the generated canvas element. When not provided during construction, insertInPage() must be invoked
  • onUpdate is a function that will be called prior to rendering all sprites. This function can be used to synchronize a Sprite with its model, for instance in a game loop (also see Sprite.update() and throttled updates)
  • onResize is a function that will be called whenever the Canvas has resized
  • debug is a boolean that specifies whether or not all sprites should render their bounding box for debugging purposes

public methods

loadResource( id: string, source: ImageSource ): Promise<Size>

Registers given source (of various type) into the Canvas so it can be referenced by provided id. The process is async as the resource is loaded and converted in a ImageBitmap instance. Returns a Size Object defining the dimensions of the bitmap once it is loaded.

getResource( id: string ): Promise<ImageBitmap | undefined>

Retrieves a reference to the created ImageBitmap for a resource registered under provided id.

disposeResource( id: string ): void

Unregisters a previously registered resource and frees allocated memory.

getContent( resourceId?: string ): Promise<HTMLCanvasElement>

Retrieves a new Canvas instance that represent the current visual state of either the entire Canvas (when no resourceId is provided) or of the Bitmap resource registered under resourceId when provided. The resulting Canvas dimensions will be equal to the source content. This method can be used when necessary to create a snapshot of the Canvas contents or when needing to do manipulations on 2D context or ImageData.

getRenderer(): IRenderer

Retrieves a reference to the IRenderer instance that is rendering this Canvas contents.

insertInPage( container: HTMLElement ): void

Will add the canvas into the HTML page by appending its generated HTMLCanvasElement into the supplied container (which is a DOM node / HTML Element). This will make the Canvas actually visible on-screen ;-)

getElement(): HTMLCanvasElement

Will return the HTMLCanvasElement which is representing the contents of zCanvas in the DOM.

preventEventBubbling( value: boolean )

Where value is a boolean stating whether or not all DOM interaction events that have been captured by the canvas should prevent their default behaviour and stop their propagation.

addChild( child: Sprite ): Canvas

This will append the given Sprite to the display list of the Canvas. As such, the visual representation of the Sprite will be rendered on the screen. This function returns a reference to the Canvas-instance the Sprite was added to (allowing you to chain operations).

removeChild( child: Sprite ): Sprite

Will remove the given sprite from the display list of the canvas (if it was present). Given Sprite child is returned.

getChildAt( index: number ): Sprite

Will retrieve the sprite from the display list at the given index number.

removeChildAt( index: number ): Sprite

Will remove a sprite at the given index number from the display list.

numChildren(): number

Will return the amount of children present on the canvas' display list. Note this will NOT return the amount of children present within the child sprites individual display lists.

getChildren(): Sprite[]

Will return an array of Sprite instances that are present at the lowest level of the Canvas' display list.

contains( child: Sprite ): boolean

Whether the given Sprite is present on the Canvas' display list.

invalidate(): void

When the Canvas isn't animatable it doesn't continuously render upon each requestAnimationFrame. This method should be invoked whenever the state of the Canvas has changed (e.g. when the visual contents should change). This method will invoke a new render request which updates the visual contents of the Canvas. This method is proxied and will wait for the next requestAnimationFrame before updating, as such repeated invocations of this method will only execute the resulting render once (when the animation frame callback fires) and not repeatedly for each invocation. Note: when adding/removing children to/from the Canvas this method is called automatically.

getFrameRate(): number
setFrameRate( number ): void

Will get and set the frame rate configured for the canvas instance.

getActualFrameRate(): number

Will return the actual frame rate achieved by the Canvas in the environment it is running in. Can be used for performance benchmarks.

getRenderInterval(): number

Will return the time (in milliseconds) between each frame at the current canvas frame rate. This can be queried by Sprites in case they require perfectly timed behaviour (NEVER use setTimeout or setInterval as the Canvas' render loop is strictly timed and provides Sprites with all the values you need for calculating elapsed time!).

getSmoothing(): boolean
setSmoothing( value: boolean ): void

Toggle the smoothing of the Canvas' contents. For pixel art-type graphics, setting the smoothing to false will yield crisper results. Setting it to true will result in the Canvas contents be anti-aliased (better for photographic content). By default smoothing is enabled.

getWidth(): number

Retrieves the width of the Canvas.

getHeight(): number

Retrieves the height of the Canvas.

setDimensions( width: number, height: number ): void

Updates the dimensions of the Canvas to match the given width and height.

getViewport(): Viewport | undefined
setViewport( width: number, height: number ): void
panViewport( x: number, y: number, broadcast?: boolean = false ): void

Define the optional viewport in which the Canvas contents will be rendered. The viewport is defined as a bounding box. When not defined, the Canvas is rendered in its entierity. See Rendering large content within a fixed viewport.

setBackgroundColor( value: string ): void

Sets a background color for the canvas. Given value (string) can be either hexadecimal (e.g. #FF0000) or RGBA (e.g. rgba(255,0,0,1)). By default zCanvas is constructed with a transparent background.

isAnimatable(): boolean
setAnimatable( value: boolean ): void

Returns whether the Canvas is animatable. The setter sets the animatable state to boolean value. When true, the Canvas will now render on each requestAnimationFrame. When false, only when invalidate() is invoked either directly or via addition/removal of children in the display list).

scale( xFactor: number, yFactor?: number ): void

Scale the contents of the Canvas by given factors (yFactor will default to match xFactor when not specified). This can be used to create a full-screen canvas where the content is in fact at a smaller scale (for instance: for a pixel art type game you can afford to have the canvas be at a low resolution and use this method to fill the screen - you might want to disable smoothing there for crisp results though -).

stretchToFit( value: boolean ): void

Given boolean value indicates whether the canvas should stretch to fit the available window dimensions. When true, the width and height defined in the constructor/setDimensions() is used to calculate the dominant axis in relation to the actual window width and height. The canvas will blow up to fill the screen without distorting the canvas contents and getWidth() and getHeight() will return the calculated dimensions. Note: the Canvas container must have the correct CSS positioning to make it actually full screen (e.g. mind the margins and paddings of parent containers!)

Unless stretchToFit was specified during construction of the Canvas, this method has to be invoked manually whenever the orientation/window size changes. Only call this manually when you desire to maintain this logic on your own terms. Preferably, construct the Canvas with autoSize and stretchToFit enabled when embedding a Canvas in a full-size container.

setFullScreen( value: boolean, stretchToFit = false ): void

Display the Canvas in full-screen mode. When stretchToFit is false, the ratio of the specified Canvas dimensions is retained. When true, the Canvas will stretch to fill the screen. NOTE always use stretchToFit when you are using pointer events with the Canvas, otherwise the pointer events will not correspond to the correct screen space (a notorious "feature" of fullscreen mode across browsers!)

getCoordinate(): DOMRect

Retrieves the bounding box of the Canvas' HTML element inside the DOM.

pause( isPaused: boolean ):void

Pauses the render cycle of an animated Canvas. When paused, no update() or draw() calls are made to the Sprites, essentially freezing the Canvas. Note: zCanvas automatically pauses rendering when the page isn't visible (for instance user opens different tab), and automatically unpauses when visibility returns.

dispose(): void

Invoking this method will clean up all listeners attached to the canvas and in turn invoke the disposal of all added children, the Collision class and dispose all resources registered using loadResource().

public properties

collision: Collision

Instance of the Collision class which can be used to resolve collisions between Sprites.

bbox: BoundingBox

The Bounding Box describing the Canvas bounds.