创建具有背景图像的画布,动态更新文本,然后保存画布? [英] 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.
这是我一直在做的一个例子: https://jsfiddle.net/qrzd395p/
Here's an example of what I've been doing: 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;
}
然后保存:
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
但是,一旦我对其进行动态更新,就无法将图像转换为png进行保存.我尝试重新设置背景图片,但这也不起作用.
However once I've updated it dynamically I can't convert the image to a png for saving. I've tried re-setting the background image but this does not work either.
经过编辑以添加我得到的错误:未捕获的SecurityError:无法在'HTMLCanvasElement'上执行'toDataURL':可能无法导出污染的画布."
Edited to add the error I get: "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported."
任何帮助将不胜感激.
推荐答案
来自上一个回答
当图像从与当前域不同的域加载到画布上时,发生污染的画布.之后,画布将无法保存到数据URL.
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.
解决方案:
将所有与页面相关的文件(.html,.jpg,.js,.css等)放置在桌面上(而不是子文件夹中).
Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).
将图像发布到支持跨域共享的网站(例如 dropbox.com).确保将图像放在Dropbox的公用文件夹中 并在下载图片时设置跨原点标记(var img = new Image(); img.crossOrigin ="anonymous" ...)
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" ...)
在开发计算机上安装Web服务器(IIS和PHP Web 服务器都有免费版本,可以在本地计算机上很好地工作.
Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).
这篇关于创建具有背景图像的画布,动态更新文本,然后保存画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!