Richard Gibson
Richard Gibson

Reputation: 11

toDataURL on dynamically added image/canvas

I'm trying to retrieve the base64 data url of an image. I've had success using the HTML canvas' toDataUrl method, on an image with crossOrigin set to anonymous to circumvent tainted-canvas problems.

However, it only works with a static, hard-coded image drawn to the canvas. If I programatically add an image to the DOM in JS and draw that to the canvas, it seems to ignore the Anonymous crossOrigin property and fail due to tainted canvas.

Example

var canvas = document.createElement('canvas');
canvas.width = 200; 
canvas.height = 200;

var img = document.createElement('img');
img.src = "https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-9/18010130_1691474777821328_8505053465237696429_n.jpg?oh=a75b5a83d1930cd8b7e38062b6f08e89&oe=594E6B6F"
img.crossOrigin = "Anonymous";
img.id = "doesntWork";
img.width = 200
img.height = 200
img.onload = function() {
  var ctx = canvas.getContext("2d"); 
  /*ctx.drawImage(document.getElementById("works"), 0, 0);
  console.log(canvas.toDataURL());*/ //--- hardcoded image drawn to canvas, toDataURL works
  ctx.drawImage(document.getElementById("doesntWork"), 0, 0);
  console.log(canvas.toDataURL()); //--- dyanmically added image drawn to canvas, fails
}
document.body.appendChild(img);
<img src="https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-9/18010138_1692193031082836_7096469518601268674_n.jpg?oh=5f125a7ec2fbf6dcf05a86481881780e&oe=59900564" crossOrigin="Anonymous"id="works" width="200" height="200">

http://jsfiddle.net/PPN7Q/156/

Upvotes: 0

Views: 865

Answers (1)

SeregPie
SeregPie

Reputation: 1253

The attribute crossOrigin is read only for the DOM elements. Use the class Image instead. Let the rest of your code as it is.

var img = new Image();
img.crossOrigin = 'anonymous'; // or img.setAttribute('crossOrigin', 'anonymous');
img.src = 'https://...';

Upvotes: 1

Related Questions