How to print canvas to data URL

Data URLIt is a useful function provided by the browser.

We can have an image instead of referencing file system files, for example

<img src="image.png" />

It embeds the image in the HTML itself, as shown below:

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

where is itRubbishThe part consisting of seemingly random letters and numbers is very long.

I am playingCanvas APIDynamically generate images, I stumbled upontoDataURL()Methods of the Canvas object:


I think this is particularly useful when creating server-side images and want to provide services in web pages generated on the server-side.

All from the Node.js process.

In particular, usecanvas npm packageWe can initialize the canvas:

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

Draw into it, for examplectx.fillText('Hello, World!', 50, 100)Then callcanvas.toDataURL()Generate the data URL of the image, and then we can append it to the HTML in the string as follows:

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

Of course, except for now, you can perform the same operations on the front endcanvasObject is a reference to an object<canvas>The HTML element you want to draw:

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

Download mine for freeNode.js manual

More node tutorials: