当尝试将图像绘制到 Canvas 上,然后将 Canvas 保存到图像时,出现以下错误:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
var picture = new Image();
picture.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/800px-Smiley.svg.png";
var canvas = document.getElementById("background");
var context = canvas.getContext("2d");
function generate(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = canvas.width;
ctx.canvas.height = canvas.height;
ctx.fillStyle = "red";
ctx.rect (0, 0, 40, 40);
ctx.fill();
ctx.drawImage(picture,0,0);
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = ctx.canvas.toDataURL("image/png");
}
function draw(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0,0,100,100,0,0,100,100);
}
function play(){
generate();
setInterval(function(){draw();}, 0.0333);
}
window.onload = function(){
if(picture.complete)play();
else picture.onload = play;
}
<canvas id="background" width=500 height=500></canvas>
我知道这与在 Canvas 上绘制图像有关,因为当删除该行后,一切都正常,您可以看到红色框:
var picture = new Image();
picture.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Smiley.svg/800px-Smiley.svg.png";
var canvas = document.getElementById("background");
var context = canvas.getContext("2d");
function generate(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = canvas.width;
ctx.canvas.height = canvas.height;
ctx.fillStyle = "red";
ctx.rect (0, 0, 40, 40);
ctx.fill();
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = ctx.canvas.toDataURL("image/png");
}
function draw(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0,0,100,100,0,0,100,100);
}
function play(){
generate();
setInterval(function(){draw();}, 0.0333);
}
window.onload = function(){
if(picture.complete)play();
else picture.onload = play;
}
<canvas id="background" width=500 height=500></canvas>
我读过其他问题,解决方案是“只需添加 image.setAttribute('crossOrigin', 'anonymous');
”(我已经这样做了)或将它们放在同一目录中(我通过将这两个文件放在桌面上尝试了这一点),但似乎都没有帮我解决一下。
有解决办法或替代方法吗?我想做的就是将多个图像绘制到一张图像上。 (红框只是为了展示。)
最佳答案
I tried this by placing both files on desktop
没有。您需要一个 Web 服务器并在 http://
(或 https://
)中打开文件,以便将它们视为同一来源。当您在 file://
中打开文件时,即使您从同一目录提供它们,它们也不会被视为同源。
关于javascript - 使用drawImage时“可能无法导出受污染的 Canvas ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840250/