Explain Codes LogoExplain Codes Logo

Get image data URL in JavaScript?

javascript
canvas
data-url
image-loading
Nikita BarsukovbyNikita Barsukov·Feb 8, 2025
TLDR

To convert an image to a Data URL in JavaScript, leverage the Canvas API and the toDataURL() function:

function toDataUrl(src, callback) { var img = new Image(); // a newborn baby image img.crossOrigin = 'Anonymous'; // it's a spy! 😎 img.onload = function() { // wait until the baby image grows up (fully loads) var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = img.naturalWidth; // real size matters canvas.height = img.naturalHeight; ctx.drawImage(img, 0, 0); // it's picture time! callback(canvas.toDataURL()); // voila! a beautiful data URL ready for adoption }; img.src = src; } // Example usage: toDataUrl('image.jpg', dataUrl => console.log(dataUrl));

Remember: Ensure the cross-origin resource sharing (CORS) is handled properly for images from different domains.

Cracking the code

Image formats: don't judge a book by its MIME type

Different image formats require different handling. Check the original image format before transforming it into a Data URL. Remember, by default, toDataURL() generates a PNG image. Change the format like this:

callback(canvas.toDataURL('image/jpeg')); // Because JPEG doesn't want to be a PNG

Note the compatibility issues with JPEG images in older Firefox versions. The time machine doesn't always work well with JPEG!

CORS: the strict border control for your images

View the crossOrigin property as your image's passport. When dealing with images from different domains, CORS check points are a must:

img.crossOrigin = "anonymous"; // Makes the image a super-spy with a fake passport

Check if the hosting server supports CORS. Blocked at the border? Blame the CORS, not the image!

Making friends with Greasemonkey scripts

Greasemonkey userscripts might require some tweaks to make the Canvas method work. Think of it like fitting a square HTML box into a circular Greasemonkey hole.

Privacy: because nobody likes stalkers

Canvas fingerprinting uses canvas data to track users. Remember, what happens on canvas, stays on canvas (privacy concerns), unless explicitly asked!

Fetch me an image, pretty please?

Fetch API can fetch you images, not coffee. Convert a fetched blob into a Data URL as shown:

fetch('image.jpg').then(response => response.blob()).then(blob => { var reader = new FileReader(); reader.onload = function() { console.log(reader.result); // DING! Your image is served as a data URL, sir. }; reader.readAsDataURL(blob); });

A new method in town: meet Mr. toDataURL

You can add toDataURL method directly to HTMLImageElement. Here's the secret handshake:

Object.defineProperty(HTMLImageElement.prototype, 'toDataURL', { value: function(callback) { toDataUrl(this.src, callback); // Now, every image knows the toDataURL dance! } });

The practical side of things

Throughout your journey, remember these navigational tips:

  1. Image Loading: Wait for the onload event before painting your image on the canvas.

  2. Data URL Prefix: To get the raw base64 string, just slice 'n dice the Data URL prefix:

    var base64 = dataUrl.split(',')[1];
  3. Re-encoding Variance: Converting image to "image/jpg" may slightly alter the image.

References