Skip to content

How to load an image in an HTML canvas

New Course Coming Soon:

Get Really Good at Git

I was using the canvas npm package to draw an image server-side using the Canvas API.

Note: this is how to work with images in a canvas in Node.js, not in the browser. In the browser it’s different.

Load the loadImage() function

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 call loadImage(), which returns a promise when the image is loaded:

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

})

You can also use, inside an async function:

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

Once you have the image, call drawImage and pass it with the x, y, width and height parameters:

context.drawImage(image, 340, 515, 70, 70)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: