How to load images in HTML canvas

I am usingcanvasnpm package to draw server-side images using Canvas API.

Note: This is the way to use the image in the canvas in Node.js (not the browser). It is different in the browser.

loadloadImage()Features

const { createCanvas, loadImage } = require('canvas')

Create the canvas:

const width = 1200
const height = 630

const canvas = createCanvas(width, height) const context = canvas.getContext(‘2d’)

Then callloadImage(), It will return a promise when loading the image:

loadImage('./logo.png').then(image => {

})

You can also use in asynchronous functions:

const image = await loadImage('./logo.png')

After you have the picture, please calldrawImageAnd pass it along with the x, y, width and height parameters:

context.drawImage(image, 340, 515, 70, 70)

Download mine for freeJavaScript beginner's manual


More js tutorials: