[英]Create a canvas with background image, dynamically update the text, then save the canvas?
I'm trying to create a canvas with a background image and text, update the text content via user input on button click, then convert that updated canvas to an image in order to save it. 我试图用背景图像和文本创建画布,单击按钮时通过用户输入更新文本内容,然后将更新后的画布转换为图像以保存它。
Here's an example of what I've been doing: https://jsfiddle.net/qrzd395p/ 这是我一直在做的一个例子: 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);
}
If I don't assign a background image I can convert the canvas to an image using the following code: 如果不分配背景图像,则可以使用以下代码将画布转换为图像:
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
Then to save: 然后保存:
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
However once I've updated it dynamically I can't convert the image to a png for saving. 但是,一旦动态更新,就无法将图像转换为png进行保存。 I've tried re-setting the background image but this does not work either.
我尝试过重新设置背景图片,但这也不起作用。
Edited to add the error I get: "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported." 编辑并添加了我得到的错误:“未捕获的SecurityError:无法在'HTMLCanvasElement'上执行'toDataURL':可能无法导出污染的画布。”
Any help would be appreciated. 任何帮助,将不胜感激。
From a previous answer 来自先前的答案
A tainted canvas occurs when images are loaded onto a canvas from a different domain than a current one. 当将图像从与当前域不同的域加载到画布上时,就会出现受污染的画布。 After that the canvas cannot be saved to a data URL.
之后,画布将无法保存到数据URL。
Solutions: 解决方案:
Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).
将所有与页面相关的文件(.html,.jpg,.js,.css等)放在桌面上(而不是子文件夹中)。
Post your images to a site that supports cross-domain sharing (like dropbox.com).
将您的图像发布到支持跨域共享的网站(例如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" ...)
确保将图像放入Dropbox的公用文件夹中,并在下载图像时设置交叉原点标记(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).
在开发计算机上安装Web服务器(IIS和PHP Web服务器都有免费版本,它们可以在本地计算机上正常运行)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.