# How to print a canvas to a data URL

> Learn how to print a canvas to a data URL in Node.js using the canvas npm package and toDataURL(), then embed the generated image directly in your HTML.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-04-05 | Topics: [Node.js](https://flaviocopes.com/tags/node/) | Canonical: https://flaviocopes.com/node-print-canvas-to-data-url/

[Data URLs](https://flaviocopes.com/data-urls/) are a useful feature provided by browsers. 

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

```html
<img src="image.png" />
```

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

```html
<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](https://flaviocopes.com/canvas/) to generate an image dynamically, and I stumbled upon the `toDataURL()` method of the Canvas object:

```js
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](https://flaviocopes.com/nodejs/) process.

In particular, using the [canvas npm package](https://www.npmjs.com/package/canvas) we can initialize a canvas:

```js
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:

```js
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:

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