我试图检索图片的base64数据网址。我已成功使用HTML画布' toDataUrl方法,在crossOrigin设置为匿名的图像上,以避免受污染的画布问题。
但是,它仅适用于绘制到画布的静态硬编码图像。如果我以编程方式将一个图像添加到JS中的DOM并将其绘制到画布上,它似乎忽略了Anonymous crossOrigin属性,并且由于受污染的画布而失败。
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">
&#13;
答案 0 :(得分:1)
属性crossOrigin
仅对DOM元素是可读的。请改用班级Image
。让其余的代码保持原样。
var img = new Image();
img.crossOrigin = 'anonymous'; // or img.setAttribute('crossOrigin', 'anonymous');
img.src = 'https://...';