-
Notifications
You must be signed in to change notification settings - Fork 4
Legacy API Legacy migration
Should you for whatever reason wish to use the 5.1.10
version of zCanvas (or below), you can find the original API here. If you wish to know what to update when migrating from an older version to 6.0.0
and up you can read the migration steps.
In an nutshell, these are the biggest changes:
-
Collision
is no longer a separate export of the zcanvas package, but a property of theCanvas
class -
Collision.getChildrenUnderPoint()
is renamed toCollision.getChildrenInArea()
-
Sprite.draw()
no longer receives a reference to the Canvas context, but rather anIRenderer
instance. All context calls should be replaced with public methods of the IRenderer API -
CanvasRenderingContext2D.drawImage()
-calls with the 9-arity version of the method should be replaced withIRenderer.drawCroppedImage()
-
Sprite.setBitmap()
no longer exists and should be replaced withSprite.setResource()
instead. This means using theloadResource
method of theCanvas
class to register resources first - several protected properties of the
Canvas
andSprite
classes have been renamed. But you should only really use the getter / setter accessors anyway (!)
The core actor of the zCanvas library. Creating an instance of zCanvas.canvas() creates a HTMLCanvasElement that can be inserted into your document to render your graphics. The zCanvas.canvas object then acts as an API to interact with the canvas, add Sprites, etc.
zCanvas.canvas( options: object )
Constructs a new zCanvas.canvas-instance. The options argument is an Object that supports the following properties (all of which are optional):
{
width: number,
height: number,
fps: number,
scale: number,
backgroundColor: string,
animate: boolean,
smoothing: boolean,
stretchToFit: boolean,
preventEventBubbling: boolean,
parentElement: Element,
onUpdate: Function,
viewport: { width: number, height: number },
handler: Function,
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 is only applies when the canvas is animateable.
- scale defines the scale factor of the canvas, this defaults to 1 (also see setScale())
- backgroundColor defines the background color of the canvas, this defaults to null for transparency (also see setBackgroundColor())
- 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 render/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), this will always rescale on window resize / orientation change. See stretchToFit().
- preventEventBubbling specifies whether the canvas should prevent events to bubble down (defaults to false)
- parentElement is a DOM Element that be the container of the generated canvas element. When null 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).
- viewport is an Object describing the optional viewport dimensions (see setViewport() or rendering large content within a fixed viewport).
- handler is a Function which is invoked on certain state changes (e.g. viewport positioning) which can be used to sync zCanvas state externally.
- debug is a boolean that specifies whether or not all sprites should render their bounding box for debugging purposes.
insertInPage( container: HTMLElement )
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 -element which will render the contents of zCanvas in the DOM. This element is created upon construction of a new zCanvas.canvas instance and can be appended to your page by using node.appendChild( zCanvasInstance.getElement() ); where node is a HTMLElement (use of insertInPage() is recommended).
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 (this is false upon construction).
addChild( aChildSprite: Sprite ): Canvas
This will append the given sprite (an instance of zCanvas.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 zCanvas.canvas-instance the sprite was added to (allowing you to chain operations).
removeChild( aChildSprite: Sprite ): Sprite
Will remove the given sprite from the display list of the canvas (if it was present). Given Sprite aChildSprite 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(): Array<Sprite>
Will return an array of Sprite-Objects that are present at the lowest level of the canvas' display list.
contains( aChildSprite: Sprite ): boolean
Whether the given sprite is present on the canvas' display list.
invalidate()
If the canvas isn't animatable (and as such doesn't 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 zCanvas. 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
Will return the frame rate configured for the canvas instance.
getActualFrameRate(): number
Will return the actual frame rate achieved by zCanvas on 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 framerate. This can be queried by Sprites in case they require perfectly timed behaviour (NEVER use setTimeout or setInterval as zCanvas' render loop is strictly timed and the only indiciation your need for calculating elapsed time!).
setSmoothing( value: boolean )
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.
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 no defined, the Canvas is rendered in its entiriety. 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
Returns whether the zCanvas is animatable (when false, the zCanvas will require manual rendering when changing its visual contents by invoking the invalidate()-method directly or via addition/removal of children in the display list).
setAnimatable( value: boolean ): void
Sets the animatable state to boolean value. When true, the canvas will now render on each requestAnimationFrame. When false, only when invalidate() is invoker either directly or via addition/removal of children in the display list).
drawImage(
imageSource: HTMLImageElement|CanvasElement,
x: number,
y: number,
width: number,
height: number,
optSourceX?: number,
optSourceY?: number,
optSourceWidth?: number,
optSourceHeight?: number
)
A safe method to draw the contents of given HTMLImageElement imageSource onto the Canvas in that this method sanitizes all values to ensure no IndexSizeErrors occur (e.g. when image dimensions are 0 or negative / clipped contents exceed the canvas size / source clipping region exceeds image dimensions). In other words: a fail safe method to resolve a bigger problem in your code ;) x and y define the destination coordinate of the image, width and height define the destination size of the image.
The remaining arguments are optional and should be used when you want to render only a specific part of given source image (as opposed to rendering the entire image). aOptSourceX and aOptSourceY define this alternative rectangle's coordinate (relative to the contents of imageSource) and aOptSourceWidth and aOptSourceHeight define the dimensions of the alternative rectangle (relative to the contents of imageSource).
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 -).
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.
dispose(): void
Invoking this method will clean up all listeners attached to the canvas and in turn invoke the disposal of all added children.
zCanvas.sprite( options )
Will construct a new zCanvas.sprite instance. The options argument is an Object that supports the following properties (all of which are optional except for width and height):
{
x: number,
y: number,
width: number,
height: number,
bitmap: Image|HTMLCanvasElement|string,
collidable: boolean,
interactive: boolean,
mask: boolean,
sheet: Array.<{ row: number, col: number, amount: number, fpt: 5, onComplete: Function }>,
sheetTileWidth: number,
sheetTileHeight: number
}
- x and y define the coordinates of the sprite (defaults to 0, 0) while required properties width and height describe the dimensions it occupies on the canvas.
- bitmap can be either:
- String (either base64 encoded image data, or URL to local Blob or remote file)
- HTMLImageElement
- HTMLCanvasElement
Not passing an bitmap 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).
- 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 spritesheet based rendering for the sprites Bitmap. See Spritesheet based animation for more details
- sheetTileWidth and sheetTileHeight are required when sheet is defined
getDraggable(): boolean
setDraggable( value: boolean, optionalKeepInBounds: boolean = false ): void
Get/set the draggable mode of this sprite. If boolean value is true, this sprite listens to mouse / touch events and can be dragged as long as the mouse / touch pointer is held down. optionalKeepInBounds is another boolean indicating whether this sprites must remain within the bounds of: either the zCanvas.canvas or the manually set constraint (more on the constraint later), this prevents the sprite from being moved off-screen.
getX(): number
setX( value: number ): void
Get and set the x-coordinate of the bounding box of the sprite.
getY(): number
setY( value: number ): void
Get and set the y-coordinate of the sprites bounding box.
getWidth(): number
setWidth( value: number ): void
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.
getHeight(): number
setHeight( value: number ): void
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.
getBounds(): { left: number, top: number, width: number, height: number }
Returns an Object describing the bounding box the sprite occupies on the canvas (contains properties "left" and "top" describing the x- and y-coordinate and properties "width" and "height" describing the width and height).
setBounds( left: number, top: number, width: number, height: number ): void
Sets the bounding box values of the sprite to given numerical values left, top, width and height.
getInteractive(): boolean
setInteractive( value: boolean ): void
Get and set the interactive state of the sprite to value. When true, this sprite can respond to user interactions such as mouse / touch events.
update( timestamp: DOMHighResTimeStamp, framesSinceLastUpdate: number ): void
This is the method that is invoked by the zCanvas.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 value timestamp 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. 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.
(!) This method will NOT be invoked if zCanvas has been constructed with a custom onUpdate-handler specified.
draw( canvasContext: CanvasRenderingContext2D, viewport: object = null ): void
This is the method that will actually render the sprite onto the zCanvas.canvas so we can actually see it on screen. This method shouldn't be invoked manually as it is invoked by the zCanvas' render cycle. The canvasContext is a reference to the 2D-context of the canvas on which we can render the visual representation of the sprite, viewport is a reference to the zCanvas viewport (when defined). By default, this method will render the contents of the sprites associated Bitmap at the sprites bounding box relative to the canvas / optional viewport position. If a spritesheet was defined for the sprite, this method will render the appropriate tile in the Bitmap.
insideBounds( x: number, y: number ): boolean
Verifies whether given coordinate is inside the Sprite bounds (comparing with the bounding box supplied by getBounds()
). This is used internally by handleInteraction()
to determine whether a Sprite should respond to an event. Can be overridden for custom logic, for instance when your sprite uses transformations during render.
collidesWith( anotherSprite: Sprite ): boolean
Queries whether the given zCanvas.sprite anotherSprite collides with this sprite-instance and returns a boolean value. This collision checks whether the bounding box of the given sprite overlaps the 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 ): { left: number, top: number, width: number, height: number }
If the sprite collides with given anotherSprite, this method will return a rectangle Object with numerical properties left, top, width and height. These properties describe the intersection area where the collision between the two sprites occurs. If the sprites aren't colliding, null is returned.
collidesWithEdge( anotherSprite: Sprite, edge: number ): 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 object, providing it with anotherSprite that is outside of this range will lead to unexpected, inaccurate results.
getBitmap(): HTMLImageElement|HTMLCanvasElement
Retrieves the HTMLImageElement or HTMLCanvasElement that describes the sprites contents.
setBitmap( image: string|HTMLImageElement|HTMLCanvasElement, optionalNewWidth: number, optionalNewHeight: number ) : Promise<void>
Updates / replaces the image contents of the sprite (for instance: to swap spritesheets). Like in the constructor, image can be either a String, HTMLImageElement or HTMLCanvasElement. optionalNewWidth and optionalNewHeight are numerical values which can be supplied in case the bounding box dimensions of the sprite are to be altered to match the new image source. Note: this method is async when given image is an Image element or String data source (as it needs to be resolved first to verify the actual dimensions). Use async/await syntax in the case your code requires the bitmap to be ready (the zCanvas render routine will automatically update when the image has loaded).
setSheet( sheet: Array<Object>, width?: number, height?: number ): void
Updates / replace 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 Spritesheet based animation for more details.
switchAnimation( sheetIndex: number )
Switches the current animation that should be playing in this sprites spritesheet. Given number sheetIndex defines the index in this sprites sheet-Array to use (also see Spritesheet based animation)
setParent( anotherSprite: Sprite|Canvas ): void
Sets a reference to the parent sprite in case this sprite is stacked onto the display list of another sprite. Should never be invoked manually but is invoked automatically during addChild() / 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.
setCanvas( zCanvas: Canvas ): void
Stores a reference to the zCanvas.canvas instance that will be rendering this sprite.
setConstraint( left: number, top: number, width: number, height: number ): void
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 zCanvas.canvas dimensions (when setCanvas() is invoked) but this method can be invoked to override it to a custom Rectangle where numerical values aLeft and aTop describe its x- and y-coordinates and aWidth and aHeight describe its dimensions.
getConstraint(): { left: number, top: number, width: number, height: number }
Returns the constraint the sprite is bound to. Returns an Object with numerical properties left, top, width and height.
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.
dispose(): void
Invoking this method will remove this sprite from its parents display list, clean up this sprites display list as well as recursively invoke the disposal of all its children.
These are invoked by the zCanvas.canvas when applicable (for instance "handleMove()" is 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: Event ): 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.
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 zCanvas.canvas containing the sprite. If the sprite is not present on a display list (either of the zCanvas.canvas or on another sprite that is present on the canvas) this will be null.
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.
These are used internally:
updateAnimation( framesSinceLastRender: number )
If the sprite has a spritesheet, this is invoked by the update()-method prior to rendering the sprites contents (using draw()). This method will verify whether to step between the individual tiles in a spritesheet.
drawOutline( canvasContext: CanvasRenderingContext2D )
Can be used for debugging purposes. This draws an outline (representing the sprites bounding box) onto the given canvasContext (is the 2d context of a HTMLCanvasElement).
zCanvas.collision is a helper Object that provides convenience methods to resolve collisions between sprite Objects.
Collision is an Object with the following methods:
Collision.pixelCollision(
sprite1: Sprite,
sprite2: Sprite,
optionalReturnAsCoordinate?: boolean = false
): boolean|{x: number, y: number}
The most accurate form of collision detection: by checking at the pixel level whether pixels of two different Objects occupy the same space. It is also the most expensive form of collision detection, while the method has been optimized to use as little CPU resources as possible, it does add up (check Collision detection to determine whether this method is the one that suits your needs. Also read below on how to use caching within the Collision helper.
Given sprite1 and sprite2 should both be instances of zCanvas.sprite. This method will calculate whether the current position of both sprites causes a collision between the pixels of both sprites Bitmaps (can be transparent PNG's). Boolean value optionalReturnAsCoordinate is optional (defaults to false). When false, this method will return a boolean value true/false to indicate whether a collision has occurred, when true this method will return an Object with numerical properties x and y which determine at what offset (relative to sprite1's bounding box) the pixel collision has occurred. This can be used to accurately resolve your collisions (for instance for platform games, see demo1 listed in the README file).
Note: this method first checks whether the given sprites actually intersect at the bounding box level. If this is false, all pixel walking calculations are omitted (as the end result would be the same: no collision).
Collision.getPixelArray(
sprite: Sprite,
rect: { left: number, top: number, width: number, height: number },
pixels: Array<number>
)
Used internally by the pixelCollision-method to retrieve an Array of pixels for given zCanvas.sprite instance sprite. The pixels are not created from the entirety of given sprites Bitmap, but only for the area described in rectangle (Object w/ numerical values left, top, width and height). This can be used to more efficiently check collisions if only a small area of a sprites Bitmap is affected. Given pixels array will be sized and populated with the appropriate content (this allows pooling of the same Array instance to prevent garbage collection overhead)
Collision.getChildrenUnderPoint(
spriteList: Array<Sprite>,
x: number,
y: number,
width: number,
height: number,
optionalOnlyCollidables?: boolean = false
)
This method will return an array of zCanvas.sprite-Objects that collide at the given coordinate for the given size. spriteList should be an Array of zCanvas.sprite-Objects (such as those returned from the getChildren()-method of both the zCanvas.canvas and zCanvas.sprite objects). x, y, width and height values are all numbers and relative to the canvas pane. optionalOnlyCollidables is an optional boolean (defaults to false), when only collidables are requested, the result will only contain the sprites that are registered to be collidable (this will for instance prevent background images from appearing in the result).
By default, pixel collisions will extrapolate pixel arrays (ImageData) from Sprite Bitmaps for each invocation of pixelCollision()
. While this is automatically managed for you, it comes at the expense of requires more from the CPU upon collision detection.
This can be fine in the case you only want to detect pixel perfect collisions infrequently (for instance after releasing a dragged Sprite). If however you expect to be calling the collision tests frequently for the same object (for instance: on every frame within a game loop), you can benefit from caching. This implies you must manually control the cache Object lifetime, but the performance gains will be large (though it will consume memory instead of CPU instead). Consider this for instance for collidable terrain in a platform game.
Collision.cache( bitmap: HTMLImageElement|HTMLCanvasElement ): Promise<boolean>
Create a pixel array cache for given bitmap. This bitmap can be specified as the source bitmap for a Sprite (or even be shared among several sprites as you can pool the same image).
Collision.hasCache( bitmap: HTMLImageElement|HTMLCanvasElement ): boolean
Tests whether the Collision utility already has a cached pixel array for given bitmap
Collision.clearCache( bitmap: HTMLImageElement|HTMLCanvasElement ): boolean
Clears the cached pixel array for given bitmap and frees memory. This can be invoked whenever the sprites using the source bitmap are no longer needed in your application.
Both canvas and sprite are class instances which come with an "extend()"-method that allows you to instantly inherit their prototype into your own custom functions.
Using ES5:
var betterSprite = function( options ) {
betterSprite.super( this, "constructor", options );
};
zCanvas.sprite.extend( betterSprite );
Using ES6 classes:
import { sprite } from "zcanvas";
class betterSprite extends sprite {
constructor( options ) {
super( options );
}
}
new betterSprite() instanceof zCanvas.sprite; // === true
Is easy using ES6 classes:
class betterSprite extends sprite {
setX( x ) {
// custom stuff here...
super.setX( x ); // call original implementation
}
}
And not that bad in ES5 either:
betterSprite.prototype.setX = function( x ) {
// custom stuff here...
betterSprite.super( this, "setX", x ); // call original implementation
};
Each instance extended using zCanvas.canvas|sprite.extend() will have a super()-method available to itself. The method signature is like so:
InheritingPrototypeName.super( instanceRef, functionName, var_args... )
Where instanceRef is the reference to the sprite/canvas instance calling the function (is likely to be "this" in most cases). fuctionName describes the name of the function to call while var_args is an optional list of comma separated values that are supplied as the arguments to the functionName that is being called. Note: to call the constructor specify "constructor" as the functionName (as seen in the example above).
The extend-method is also available in each extended zCanvas.canvas|sprite prototypes, the following code as such works:
function betterSprite( options ) {
betterSprite.super( this, "constructor", options );
}
zCanvas.sprite.extend( betterSprite );
function evenBetterSprite( options ) {
evenBetterSprite.super( this, "constructor", options );
}
betterSprite.extend( evenBetterSprite );
evenBetterSprite instanceof zCanvas.sprite; // === true
evenBetterSprite instanceof betterSprite; // === true
Using ES6 classes:
import { sprite } from "zcanvas";
class betterSprite extends sprite {
constructor( name, options ) {
super( options );
this._name = name; // behaviour unique to "betterSprite"
}
setX( value ) {
// something silly, but unique to this "betterSprite"
const delta = this.getX() - value;
this.setY( this.getY() + delta );
// calls the original "setX"-method of the zCanvas.sprite base class
super.setX( value );
}
}
Using ES5:
function betterSprite( name, options ) {
betterSprite.super( this, "constructor", options );
this._name = name; // behaviour unique to "betterSprite"
this.setX = function( value ) {
// something silly, but unique to this "betterSprite"
var delta = this.getX() - value;
this.setY( this.getY() + delta );
// calls the original "setX"-method of the zCanvas.sprite prototype
betterSprite.super( this, "setX", value );
}
}
betterSprite.extends( zCanvas.sprite );