我正在尝试创建一个带有背景图像和文本的 Canvas ,通过单击按钮时的用户输入更新文本内容,然后将更新后的 Canvas 转换为图像以保存它。
这是我一直在做的一个例子:https://jsfiddle.net/qrzd395p/
var c = document.getElementById('canvas');
var context = c.getContext('2d');
var backgroundImage = new Image();
backgroundImage.onload = function() {
// Once the image has finished loading, draw the
// image and then the text.
DrawScreen();
DrawText();
};
backgroundImage.src = "http://lorempixum.com/200/200/";
function DrawScreen() {
context.drawImage(backgroundImage, 0, 0);
}
function DrawText() {
context.fillStyle = "red";
context.font = "18px sans-serif";
context.textBaseline = 'top';
context.fillText("This is a test", 50, 100);
}
如果我不分配背景图像,我可以使用以下代码将 Canvas 转换为图像:
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
然后保存:
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
但是,一旦我动态更新它,我就无法将图像转换为 png 进行保存。我尝试过重新设置背景图像,但这也不起作用。
编辑添加我收到的错误:“未捕获的安全错误:无法在“HTMLCanvasElement”上执行“toDataURL”:受污染的 Canvas 可能无法导出。”
如有任何帮助,我们将不胜感激。
最佳答案
当图像从与当前域不同的域加载到 Canvas 上时,就会出现受污染的 Canvas 。此后 Canvas 无法保存到数据 URL。
解决方案:
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). 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).
关于javascript - 创建一个带有背景图像的 Canvas ,动态更新文本,然后保存 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34664809/