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://nxjs.n8.io/logo.png');
const data = await res.arrayBuffer();
const img = await createImageBitmap(new Blob([data]));
 
const ctx = screen.getContext('2d');
ctx.drawImage(img, 0, 0);

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();
 
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