gpt4 book ai didi

javascript - 无法在 HTMLCanvasElement 上执行 toDataURL

转载 作者:行者123 更新时间:2023-11-30 09:36:26 27 4
gpt4 key购买 nike

从图像(本地文件)绘制 Canvas 后,我尝试使用命令 ctx.canvas.toDataURL("image/png")

导出它

但是有一个错误:

DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

我已经在谷歌搜索过。他们说这是克罗斯的问题。所以,我添加了命令:

image.crossOrigin = '*';

但这对我的项目没用。实际上,我的项目是在本地构建的,没有任何服务器。所以,我不知道为什么会出现跨域问题。

function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
var image = new Image();
image.onload = function() {
image.crossOrigin = '*';
resolve(image);
};
image.onerror = function() {
reject(new Error('Could not load image at ' + url));
};
image.src = url;
});


generate() {
var p1 = loadImageAsync(this.textures[1]);
var p2 = loadImageAsync(this.textures[2]);
var p3 = loadImageAsync(this.textures[3]);
var ctx = document.createElement("canvas")
.getContext("2d");
ctx.canvas.width = this.width;
ctx.canvas.height = this.height;
var rows = ~~(this.width / 70);
var cols = ~~(this.height / 70);
Promise.all([p1, p2, p3])
.then(imgs => {
for (let x = 0, i = 0; i < rows; x += 70, i++) {
for (let y = 630, j = 0; j < cols; y -= 70, j++) {
this.resource[i].forEach(item => {
switch (item) {
case 1:
ctx.drawImage(imgs[0], x, y, 70, 70);
break;
case 2:
ctx.drawImage(imgs[1], x, y, 70, 70);
break;
case 3:
ctx.drawImage(imgs[2], x, y, 70, 70);
break;
default:
}
});
}
}
//window.ctx = ctx;
this.image.crossOrigin = '*';
this.image.src = ctx.canvas.toDataURL("image/png");
});
};

最佳答案

需要在onload函数外为图片设置crossOrigin

return new Promise(function(resolve, reject) {
var image = new Image();
image.crossOrigin = '*'; //<-- set here
image.onload = function() {
resolve(image);
};
image.onerror = function() {
reject(new Error('Could not load image at ' + url));
};
image.src = url;
});

关于javascript - 无法在 HTMLCanvasElement 上执行 toDataURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com