Explain Codes LogoExplain Codes Logo

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

javascript
data-uri
base64-data
canvas-api
Anton ShumikhinbyAnton Shumikhin·Nov 16, 2024
TLDR

Here's how you extract base64 binary data with toDataURL() from a canvas. Quick note: you have to split the result with a comma(,) to get the base64 data segment.

var base64Data = canvas.toDataURL("image/png").split(',')[1];

The variable base64Data now holds the canvas image's base64-encoded binary data.

Working with various image formats

Various image formats are supported by the toDataURL method.

JPEG Extraction

For a JPEG image:

var base64Data = canvas.toDataURL("image/jpeg").split(',')[1]; // Who doesn't love a JPEG?

PNG Extraction

For a PNG image (this is default, so no need to explicitly mention "image/png"):

var base64Data = canvas.toDataURL().split(',')[1]; // Now, we're talking about a PNG!

Understanding and handling cross-origin restrictions

Cross-origin resource sharing issues can become pesky gremlins. Remember, images need to be hosted on the same domain as your application unless served with correct CORS headers.

Working with the data:URI scheme

The output you get from toDataURL is a data URI scheme.

Here's how you polish it to get the "gem", i.e., the actual base64 data:

var pureBase64Data = dataURL.split(';base64,')[1]; // Voila, here's the gem!

Use cases for base64 data

The base64 string extracted is multi-talented. It's ready for:

  • Uploading: It can walk up to a server as part of an API request.
  • Storage: Saved for later use.
  • DOM: It can be a star within an image element in the DOM.

Official References and Guides

Check out the MDN documentation for canvas.toDataURL and the Wikipedia article on the data: URI scheme for a deep dive.

Comprehensive usage and best practices

File operations and manipulation

If you need to perform operations like resizing or format conversions on the file, consider File APIs with JavaScript.

Easing canvas work with jQuery

The jCanvas plugin for jQuery users simplifies canvas manipulation. The getCanvasImage() method is like a magic wand for retrieving base64 data.

Server upload of base64 data

Directly send the base64 data in a request body for server uploads. This method is sometimes even preferred over your crush.

fetch('your-upload-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: base64Data }) }); // This base64 data is going places!

Client-side resizing

Do your server a favor: perform image resizing client-side before extracting the base64. Remember to paint the resized image onto a separate canvas before running your toDataURL(). This is your server thanking you later!