Image Processing: How to print a canvas to a data URL

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Data URLs are a useful feature provided by browsers.

We can have an image that instead of referencing a file system file, like

<img src="image.png" />

it embeds the image in the HTML itself, something like this:

<img src="data:image/png;base64,iVBORw0KGgoAA…" />

where the garbage part that’s composed by seemingly random letters and numbers is very long.

I was playing with the Canvas API to generate an image dynamically, and I stumbled upon the toDataURL() method of the Canvas object:

canvas.toDataURL()

I think that this is especially useful when you create a server-side image and you want to serve it in a web page, server-side generated.

All from a Node.js process.

In particular, using the canvas npm package we can initialize a canvas:

const { createCanvas, loadImage } = require('canvas')
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')

draw into it, using for example ctx.fillText('Hello, World!', 50, 100) and then call canvas.toDataURL() to generate the data URL for an image which we can then append to the HTML in a string, like this:

const imageHTML = '<img src="' + canvas.toDataURL() + '" />'

You can do the same on the frontend, of course, except now the canvas object is a reference to a <canvas> HTML element you are drawing to:

const canvas = document.getElementById('canvas')
//…
const imageHTML = '<img src="' + canvas.toDataURL() + '" />'

Lessons in this unit:

0: Introduction
1: How to create and save an image with Node.js and Canvas
2: How to download an image from URL in Node
3: How to download and save an image using Node.js
4: How to get an image width and height using Node
5: How to turn an image into a data URI string
6: How to download an image using Node.js
7: ▶︎ How to print a canvas to a data URL
8: Optimize images from a Node.js script
9: Calling the ImageOptim macOS app from a Node.js script