Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)
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.
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:
PNG Extraction
For a PNG image (this is default, so no need to explicitly mention "image/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:
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.
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!
Was this article helpful?