nx.js
Concepts

Images

Loading images for use with the Canvas API

Your app can load image assets and display them when used in conjunction with canvas rendering mode.

There are two primary ways to load images in nx.js:

  1. Using the createImageBitmap() function (preferred)
  2. Using the Image class

createImageBitmap()

Use the createImageBitmap() function to asynchronously load and decode an image into an instance of ImageBitmap:

const res = await fetch('https://dog.ceo/api/breeds/image/random');
const body = await res.json();
 
const imageRes = await fetch(body.message);
const data = await imageRes.arrayBuffer();
const img = await createImageBitmap(new Blob([data]));
 
// Draw image centered on screen
const ctx = screen.getContext('2d');
ctx.drawImage(img, screen.width / 2 - img.width / 2, screen.height / 2 - img.height / 2);
Screenshot

Image class

Alternatively, your app can use the Image constructor to load and decode images.

Setting the "src" property to load image data uses fetch() under the hood, so any protocol supported by fetch() is also supported by the Image class.

const img = new Image();
const ctx = screen.getContext('2d');
 
img.onload = () => {
    const ctx = screen.getContext('2d');
    ctx.drawImage(img, 0, 0);
};
 
img.src = 'https://nxjs.n8.io/logo.png';

The Image class requires using the callback pattern to load images. As such, it is recommended to use the createImageBitmap() function instead since it supports async/await syntax.

On this page