简体   繁体   English

动态添加的图像/画布上的toDataURL

[英]toDataURL on dynamically added image/canvas

I'm trying to retrieve the base64 data url of an image. 我正在尝试检索图像的base64数据URL。 I've had success using the HTML canvas' toDataUrl method, on an image with crossOrigin set to anonymous to circumvent tainted-canvas problems. 我在将crossOrigin设置为匿名以规避污染画布问题的图像上使用HTML canvas的toDataUrl方法取得了成功。

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. 如果我以编程方式在JS中将图像添加到DOM并将其绘制到画布上,则它似乎会忽略Anonymous crossOrigin属性,并且由于画布污染而失败。

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/ http://jsfiddle.net/PPN7Q/156/

The attribute crossOrigin is read only for the DOM elements. 属性crossOrigin对于DOM元素是只读的。 Use the class Image instead. 请改用Image类。 Let the rest of your code as it is. 让其余的代码保持原样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM