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
  • 572,313
  • 128
  • 898
  • 1,281
Mia
  • 5,970
  • 10
  • 44
  • 77

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
  • 6,451
  • 11
  • 52
  • 82