/

How to Load an Image in an HTML Canvas

How to Load an Image in an HTML Canvas

When working with the canvas npm package to draw images server-side using the Canvas API, you may need to load an image onto the canvas. Here’s a step-by-step guide on how to achieve this in Node.js:

  1. Start by loading the loadImage() function from the canvas package:
1
const { createCanvas, loadImage } = require('canvas');
  1. Create the canvas with the desired width and height:
1
2
3
4
5
const width = 1200;
const height = 630;

const canvas = createCanvas(width, height);
const context = canvas.getContext('2d');
  1. Call the loadImage() function and handle the promise returned when the image is loaded:
1
2
3
loadImage('./logo.png').then(image => {
// Image loaded successfully, you can now proceed with drawing on the canvas
});
  1. Alternatively, if you are working within an async function, you can use the await keyword to simplify the code:
1
const image = await loadImage('./logo.png');
  1. Once you have the loaded image, you can use the drawImage method to place it on the canvas. Provide the image, along with the desired x and y coordinates, width, and height:
1
context.drawImage(image, 340, 515, 70, 70);

Please keep in mind that this approach is specific to loading images in a canvas on the server-side with Node.js. The process may differ when working with images in a browser environment.

Tags: image loading, canvas API, Node.js, loadImage, drawImage