How to print a canvas to a data URL
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() + '" />'download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.