Skip to content
Igor Zinken edited this page Jan 17, 2024 · 26 revisions

Sprite

The Sprite class is basically a drawable for your Canvas. Its defines a visual object and provides an API to position and transform the object, handle and delegate interaction events, etc.

constructor

Sprite( props: SpriteProps )

Will construct a new Sprite instance. The props argument is an object that supports the following properties (all of which are optional):

interface SpriteProps {
    width: number;
    height: number;
    x?: number;
    y?: number;
    rotation?: number;
    resourceId?: string;
    collidable?: boolean;
    interactive?: boolean;
    mask?: boolean;
    sheet?: SpriteSheet[];
}
  • x and y define the coordinates of the Sprite (defaults to 0, 0) while properties width and height describe the dimensions in pixels it occupies on the Canvas (defaults to 10x10)
  • rotation specifies the angle at which the Sprite is displayed (defaults to 0). Rotations are specified in degrees
  • resourceId is the id under which an asset was registered in the Canvas. When provided, this asset will be rendered as an image. Not providing this value will result in nothing being rendered on the Canvas (unless you extend this Sprite instance with custom draw()-logic (see below) and use it to draw graphics instead of rendering an image). Also see resource management.
  • collidable indicates whether this Sprite is elligible for collision checks (more on this later), this defaults to false
  • interactive indicates whether this Sprite can receive pointer interaction events (also see setInteractive(), defaults to false)
  • mask can be set to true to use the pixel content of this sprite as a mask (will affect the underlying sprites)
  • sheet can be provided to use sprite sheet based rendering. The provided values for width and height now also describe the size of each individual tile within the sprite sheet. See Sprite sheet based animation for more details

public methods

getDraggable(): boolean
setDraggable( value: boolean, optionalKeepInBounds: boolean = false ): void

Toggle the draggable state of this Sprite. If boolean value is true, this Sprite listens to mouse / touch events and can be dragged as long as the pointer is held down. optionalKeepInBounds indicates whether this Sprite must remain within the bounds of either: the Canvas or the manually set constraint (more on the constraint later), this prevents the Sprite from being moved off-screen.

getInteractive(): boolean
setInteractive( value: boolean ): void

Toggle whether this sprite should respond to user interactions such as mouse / touch events.

getX(): number
setX( value: number ): void

Manage the x-coordinate of the Sprite. When setting a new value (that differs from the current), the Canvas will automatically be invalidated to render the new state.

getY(): number
setY( value: number ): void

Manage the y-coordinate of the Sprite. When setting a new value (that differs from the current), the Canvas will automatically be invalidated to render the new state.

getWidth(): number
setWidth( value: number )

Get and set the width of the Sprite. This will also adjust the existing x coordinate to keep the Sprites center relative to the old width. The Canvas will automatically be invalidated to render the new state when setting a new value.

getHeight(): number
setHeight( value: number )

Get and set the height of the Sprite. This will also adjust the existing y coordinate to keep the Sprites center relative to the old height. The Canvas will automatically be invalidated to render the new state when setting a new value.

getBounds( getTransformed = false ): Rectangle

Returns a Rectangle instance (left, top, width and height) describing the bounding box the Sprite occupies on the Canvas. The returned Rectangle properties can be mutated externally to update the Sprites position and size (for instance, by an animation library).

The returned Rectangle always corresponds to the untransformed bounding box (as zCanvas will handle collision checks and positioning for transformed content automatically, greatly alleviating the math involved). If you however require to know the actual bounding box of a transformed (e.g. rotated or scaled) Sprite, pass true for getTransformed.

setBounds( left: number, top: number, width?: number, height?: number ): void

Sets the bounding box values of the Sprite to provided value. If the Sprite has a constraint, the values are restricted to remain within the allowed bounds.

getRotation(): number
setRotation( angleInDegrees: number, pivot?: Point ): void

Get and set the rotation of the Sprite in degrees. Optional Point pivot describes an alternative pivot point to rotate the Sprite around. When undefined, the Sprite defaults to rotating around its center.

getScale(): number
setScale( scaleFactor: number ): void

Get and set the scale factor of the Sprite.

getTransforms(): { scale: number, rotation: number, alpha: number }

Returns an instance of the transformations applied to the Sprite. The value of this object can be mutated externally (for instance to tween the transformations by an animation library).

isVisible( viewport?: Viewport ): boolean

Verifies whether the Sprite is currently visible. When viewport is undefined, the Sprite will check against the bounding box of its Canvas. Sprites outside of the viewport / Canvas' visible area are not considered visible. This can be used when you override the draw() handler in your subclass to determine whether to render the Sprites content or not. This method takes transformations (for instance scaling operations) into account.

insideBounds( x: number, y: number ): boolean

Verifies whether given coordinate is inside the Sprites bounds. This is used internally by handleInteraction() to determine whether a Sprite should respond to an event. This takes transformations into account.

collidesWith( anotherSprite: Sprite ): boolean

Queries whether given anotherSprite collides with this Sprite instance. This collision checks whether the (transformed) bounding box of the given Sprite overlaps the (transformed) bounding box of this Sprite. This is a fast operation and can suffice in most cases (e.g. shoot 'em up games). If however, one of either sprites has large transparent areas and you require maximum accuracy, it might be recommended to check collision at the pixel level.

getIntersection( anotherSprite: Sprite ): Rectangle | undefined

If the Sprite collides with given anotherSprite, this method will return a Rectangle object describing the intersection area where the collision between the two Sprites occurs. If the sprites aren't colliding, nothing is returned.

collidesWithEdge( anotherSprite: Sprite, edge: 0 | 1 | 2 | 3 ): boolean

A fast query to check whether the given anotherSprite collides with an edge of this Sprite. edge is a number with one of four possible values:

  • 0 : left
  • 1 : above
  • 2 : right
  • 3 : below

which are relative to the edge of the current Sprite instance. A use case for this method could be (in a game context) checking whether a character sprite is touching a floor sprite (by testing for edge 1, i.e. below the character sprite) and omit altering it's y-position (gravity causing it to "fall" when not touching any floor).

NOTE : this method is designed to work with the getChildrenUnderPoint()-method of the Collision-class, providing it with anotherSprite that is outside of this range will lead to unexpected, inaccurate results.

getResourceId(): string
setResource( resourceId: string, width?: number, height?: number ): void

Get and set the identifier of the asset (registered in the Canvas using loadResource()) that will be visualized by this Sprite. This an be invoked outside of the constructor to (for instance) swap sprite sheets. width and height can be supplied in case the bounding box dimensions of the Sprite are to be altered to match the new asset dimensions. Also see resource management.

setSheet( sheet: SpriteSheet[], width?: number, height?: number ): void

Updates / replaces the sheet description of the Sprite. Like in the constructor, sheet is an Array of { row: number, col: number, amount: number, fpt: 5, onComplete: Function } objects. width and height describe the size of each individual tile within the sheet. When not provided, these default to the Sprite bounds. See Sprite sheet based animation for more details.

switchAnimation( sheetIndex: number ): void

Switches the current animation that should be playing in this sprites sprite sheet. Given number sheetIndex defines the index in this sprites sheet-Array to use (also see Sprite sheet based animation)

getParent(): DisplayObject<Sprite | Canvas> | undefined
setParent( parent: DisplayObject<Sprite | Canvas> | undefined ): void

Get and set a reference to the parent (Sprite or Canvas) in case this Sprite is stacked onto a display list. Should never be invoked manually but is invoked automatically during add|removeChild()-operations.

getParent(): Sprite|Canvas

If the sprite is stacked onto the display list of another sprite, this returns the parent sprite. If the sprite was added directly onto the zCanvas.canvas display list, it will return the canvas. If the sprite is not present on any display list, this will return null.

canvas: Canvas | undefined
setCanvas( zCanvas: Canvas ): void

Get and set a reference to the Canvas that is rendering the Sprite. Is undefined when the Sprite is not added to a display list.

getConstraint(): Rectangle
setConstraint( left: number, top: number, width: number, height: number ): Rectangle

A Sprite can be constrained in its movement when dragging to ensure it remains within desired boundaries. A parent constraint specifies the boundaries of this sprites "container". this constraint will by default be equal to the Canvas dimensions but this method can be invoked to override it to a custom Rectangle where the provided values describe its bounding box.

addChild( childSprite: Sprite ): Sprite

This will append given sprite childSprite to the display list of this Sprite. As such, the visual representation of the given child sprite will be rendered onto the Canvas. This method returns the sprite given aChildSprite was appended to for chaining purposes.

removeChild( childSprite: Sprite ): Sprite

Will remove given sprite _ childSprite_ from the display list of the sprite (if it was present). This method returns the removed child.

getChildAt( index: number ): Sprite

Will retrieve a 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. This method will returned the removed sprite (for chaining purposes).

numChildren(): number

Will return the amount of children present on this sprites display list.

contains( childSprite: Sprite ): boolean

Whether the given sprite is present on this sprites display list.

update( timestamp: DOMHighResTimeStamp, framesSinceLastUpdate: number ): void

This is the method that is invoked by the Canvas render cycle just prior to calling the Sprites draw()-method. This can be used to update the state and properties of the Sprite (or its related model) prior to the next render cycle. The timestamp-value can be used for calculating properties that should change over time. Using this timestamp has the benefit that no expensive timeouts or intervallic methods have to be used and that your animations will be synced strictly to a clock, which is convenient when the application loses focus (for instance if the user switches tabs in the browser). A likely use case for this method is to update the location of a self-moving Object, or to check for collisions with other sprites and update the state accordingly (more on collision detection here).

framesSinceLastUpdate describes the amount of (requestAnimation)frames that have elapsed since the previous invocation of the update()-method, note that this is a fractional (floating point) value. This value might be of interest if you intend to use the update()-method to change the state of your (game) environment to adjust position / animation.

NOTE (!) This method will NOT be invoked if the Canvas has been constructed with a custom onUpdate-handler specified. Your onUpdate handler should thus call update() on all Sprites of the Canvas (each Sprite will recursively request an update of their child Sprites automatically).

draw( renderer: IRenderer, viewport?: Viewport ): void

This is the method that will actually render the Sprite content onto the Canvas so we can actually see it on screen. This method shouldn't be invoked manually as it is invoked by the Canvas' render cycle. renderer is a reference to the IRenderer instance used to render the visual representation of the Sprite using draw commands. viewport is a reference to the Canvas viewport (when defined). By default, this method will render the contents of the Sprites associated resource at its sprites bounding box relative to the Canvas / optional Viewport position, using its optional transformations. If a sprite sheet was defined for the Sprite, this method will render the appropriate tile from the sheets Bitmap.

If you wish to use custom rendering logic (for instance to draw shapes instead of images), this is the method to override.

dispose(): void

Invoking this method will remove this Sprite from its parents display list, clean up its display list as well as recursively invoke the disposal of all its children. Note that this will not dispose registered resources corresponding to its resourceId.

event handlers

These are invoked by the Canvas when applicable (for instance handleMove() is only invoked when the draggable state of the Sprite is set to true). As such you don't have to add custom event listeners to a Sprite, but can override these methods in your Sprite instances / deriving classes.

handlePress( x: number, y: number ): void

Invoked when the user clicks / touches this sprite. This should be seen as a "down" handler. x and y describe the coordinates of the pointer during the interaction.

handleRelease( x: number, y: number ): void

Invoked when the user releases the click / touch of this sprite. This should be seen as a "up" handler. x and y describe the coordinates of the pointer during the interaction.

handleClick(): void

Invoked when the user clicks / taps this sprite. This indicates press and release have followed each other within a 250 ms window.

handleMove( x: number, y: number ): void

Invoked when the user moves the mouse / touch pointer when the pointer is held down (i.e. "handleRelease()" hasn't fired) and the sprite is draggable. x and y correspond the coordinates of the pointer. When bounds or constraints have been imposed the default behaviour of this method will ensure the sprite remains within the visible area of the zCanvas. You're likely not going to override this unless you really know what it is you want to achieve ;)

handleInteraction( x: number, y: number, event: MouseEvent | TouchEvent ): void

Invoked by zCanvas.canvas whenever the user interacts with the canvas, this method basically performs internal checks to see whether the user interaction applies to this sprite (for instance : to start dragging). This method is only to be overridden when you need very custom behaviour in your sprite. In most cases, it will suffice to override the above handlers instead.

public properties

collidable: boolean

boolean indicating whether this sprite can collide with other sprites (will be queried by collision detection routines).

isDragging: boolean

boolean indicating whether this sprite is currently being dragged.

hover: boolean

boolean indicating whether the user is currently hovering over this sprite, note this DOES NOT mean the user is dragging (see protected property dragging) this value will ALWAYS be false if the sprite is not interactive (or when using the library on a touchscreen).

canvas: Canvas

A reference to the Canvas containing the Sprite. If the Sprite is not present on a display list (either of the Canvas or on another Sprite that is present on the Canvas) this will be undefined.

last?: Sprite
next?: Sprite

Are references to other sprite present on this sprites canvas. These are appended automatically when using the addChild() and removeChild()-methods and function as a linked list for extra speed during rendering.

protected methods

These are used internally:

protected invalidate(): void

Can be called to request an invalidation of the Canvas (triggering a re-render if it isn't automatically animating) whenever a visual property of the Sprite changes.

protected getDrawProps(): DrawProps | undefined

Retrieve a DrawProps instance used to render transformations or blending modes while rendering the Sprites content. Can be undefined if no transformations exists. Should be used only within an overridden draw()-method.

protected updateAnimation( framesSinceLastRender: number ): void

If the sprite has a spritesheet, this is invoked by the update()-method prior to rendering the sprites contents (in the draw()-method). This method will verify whether to step between the individual tiles in a spritesheet.