我正在尝试将外部图像附加到Vue.js中的画布上(尽管Vue绝对不是问题)。我正在尝试将画布dataURL保存到状态变量,以便我以后可以访问该图像(这是人们在画布上添加贴纸的游戏,在游戏结束后我希望人们看到更小版本的画布) 。不幸的是我收到错误,Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
问题是画布看到我试图保存外部图像,并说“哦不,这些图像可能是一个脚本小孩攻击,所以我不会让你”。很公平。但是,我想为了我的目的而重写这个。我试图通过在将图像添加到画布时将导入的图像上的crossOrigin设置为“Anonymous”来实现。然而,这不起作用。我不确定我怎么能解决这个问题。
这是附加到画布的图像的组件。将画布导出到URL最后。 window["imageObj" + canvasID].crossOrigin = "Anonymous";
是我用来尝试解决CORS问题的路线。
任何和所有帮助将不胜感激。我很困惑。
var canvasID = Date.now();
window["createCanvas" + canvasID] = document.createElement('canvas');
window["createCanvas" + canvasID].width = 800;
window["createCanvas" + canvasID].height = 800;
window["createCanvas" + canvasID].background = "transparent";
window["createCanvas" + canvasID].borderRadius = "3px";
window["createCanvas" + canvasID].borderColor = "black";
window["createCanvas" + canvasID].borderStyle = "solid";
window["ctx" + canvasID] = window["createCanvas" + canvasID].getContext('2d');
window["imageObj" + canvasID] = new Image();
window["imageObj" + canvasID].crossOrigin = "Anonymous";
window["imageObj" + canvasID].src = newCanvas[0][2];
window["imageObj" + canvasID].onload = function(){
window["ctx" + canvasID].drawImage(window["imageObj" + canvasID], newCanvas[0][0], newCanvas[0][1]);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(window["createCanvas" + canvasID], 0, 0);
var img = new Image;
img.crossOrigin = "Anonymous";
img.src= canvas.toDataURL('image/jpeg', 1.0);
img.onload = function(){
this.canvasImageData = img;
console.log("this.canvasImageData is ", this.canvasImageData);
}
}