Skip to content
Igor Zinken edited this page Jul 10, 2020 · 7 revisions

zCanvas.loader

zCanvas.loader is a helper Object that provides convenience methods to load Images with a callback mechanism ensuring the loaded content is ready to be rendered in/as a sprite.

Using loader

Loader is an Object with the following methods:

loadImage( source, optImage ) : Promise

Where source is a String containing either:

  • a base64 encoded representation of an Image
  • a path to a file on a remote/local origin
  • a path to a Blob URL

optImage is an optional HTMLImageElement that can be passed into the function. This Image will be updated with the new source once loading has completed, if not defined a new Image will be created by the Loader.

loadImage is asynchronous (regardless of having been supplied a base64 string - where content is theoretically available - or a URL to a remote file - which has to be downloaded - ). The reason being that having all Image data available is not the same as having an HTMLImageElement pointing to this data and actually be ready for rendering. Loader is responsible for ensuring that the Image is always ready when the callback is fired. As such, loadImage returns a Promise and is best used with async/await-syntax where applicable. The Promise will resolve with a wrapped image Object { width: number, height: number, image: HTMLImageElement }

Loader will also apply the correct crossOrigin-attribute onto the resulting HTMLImageElement when applicable (e.g. when source actually points to a URL on a server of a different origin).

(!) When storing Images on a CDN, ensure that the correct Cross Origin (CORS) headers are provided when accessing the Images, otherwise the zCanvas is not allowed to perform operations on the Image.

Sprite.setBitmap

If you are changing a Sprite's Bitmap content at runtime (using the setBitmap()-method of a Sprite), Loader is actually invoked prior to rendering the new Bitmap. This should ensure that the Sprite will wait rendering until the new Image has been downloaded and been verified to be ready for rendering.