我希望能够将 Canvas(包含来自另一个域的图像)转换为 Image。为此,据我所知,我应该使用启用 CORS 的图像(以便能够将 .toDataURL() 用于画布)。问题是如何制作启用 CORS 的图像。以下代码在第一行引发错误:Cross-origin image load denied by Cross-Origin Resource Sharing policy。
<html>
<body>
<input type="button" id="button" value="convert" onclick="onClick()" /></br>
<img id="output" />
<script>
var source = "https://www.gravatar.com/avatar/7b67c827ee1671ba3b43f4aebf6794fb?s=128&d=identicon&r=PG";
onClick = function () {
var img = document.createElement('img');
img.onload = function (e) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var url = canvas.toDataURL();
var output = document.getElementById("output");
output.src = url;
};
img.crossOrigin = 'anonymous';
img.src = source;
};
</script>
</body>
</html>