我想保存我的画布到img。我有这样一个函数:

function save() {
    document.getElementById("canvasimg").style.border = "2px solid";
    var dataURL = canvas.toDataURL();
    document.getElementById("canvasimg").src = dataURL;
    document.getElementById("canvasimg").style.display = "inline";
}

它给出了错误:

Uncaught SecurityError:未能在“HTMLCanvasElement”上执行“toDataURL”:受污染的画布可能无法导出。

我该怎么办?


当前回答

对于任何在应用服务器跨源设置后仍然在S3中遇到相同问题的人来说,这可能是浏览器缓存问题。 所以你需要确保禁用缓存并再次测试,你可以从浏览器的dev-tools ->网络选项卡->单击禁用现金选项->重试:

其他回答

似乎您正在使用的图像来自一个URL,没有设置正确的访问控制-允许起源头,因此出现了问题。您可以从您的服务器获取该映像,并从您的服务器获取它以避免CORS问题。

出于安全原因,您的本地驱动器被声明为“other-domain”,并将污染画布。

(这是因为你最敏感的信息可能在你的本地驱动器上!)

在测试时尝试以下变通方法:

Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders). Post your images to a site that supports cross-domain sharing (like dropbox.com or GitHub). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...) Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).

在我的情况下,我从我的桌面进行测试,即使在本地保存图像到子文件夹后,也有CORS错误。

解决方案:

移动文件夹到本地服务器WAMP在我的情况下。从本地服务器完美工作。

注意: 只有在本地保存图像时才有效。

在img标签中将crossorigin设置为Anonymous。

<img crossorigin="anonymous" />

如果你正在使用ctx.drawImage()函数,你可以做以下事情:

var img = loadImage('../yourimage.png', callback);

function loadImage(src, callback) {
    var img = new Image();

    img.onload = callback;
    img.setAttribute('crossorigin', 'anonymous'); // works for me

    img.src = src;

    return img;
}

在你的回调中,你现在可以使用ctx。drawImage并使用toDataURL导出它