Skip to content

How to load an image in an HTML canvas

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)

β†’ Get my JavaScript Beginner's Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about js: