0

I'm looking for an elegant way to convert an existing <img> on the document to base64 loaded <img>. So simply the src url will be converted to base64 data.

What's the best way to obtain this?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Mia
  • 6,220
  • 12
  • 47
  • 81

1 Answers1

0

I've managed to make this work! (I got the same issue.) In the code below, img is the image DOM element:

var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
img.crossOrigin = "anonymous";
canvas.getContext('2d').drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL('image/png');

The line img.crossOrigin = "anonymous"; helps to bypass CORS somehow, although I'm not sure if that's a "hack" and may be "fixed" at some point as I don't fully understand the issue with CORS here.

Community
  • 1
  • 1
YakovL
  • 7,557
  • 12
  • 62
  • 102