繁体   English   中英

创建具有背景图像的画布,动态更新文本,然后保存画布?

[英]Create a canvas with background image, dynamically update the text, then save the 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);
}

如果不分配背景图像,则可以使用以下代码将画布转换为图像:

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进行保存。 我尝试过重新设置背景图片,但这也不起作用。

编辑并添加了我得到的错误:“未捕获的SecurityError:无法在'HTMLCanvasElement'上执行'toDataURL':可能无法导出污染的画布。”

任何帮助,将不胜感激。

来自先前的答案

当将图像从与当前域不同的域加载到画布上时,就会出现受污染的画布。 之后,画布将无法保存到数据URL。

解决方案:

将所有与页面相关的文件(.html,.jpg,.js,.css等)放在桌面上(而不是子文件夹中)。

将您的图像发布到支持跨域共享的网站(例如dropbox.com)。 确保将图像放入Dropbox的公用文件夹中,并在下载图像时设置交叉原点标记(var img = new Image(); img.crossOrigin =“ anonymous” ...)

在开发计算机上安装Web服务器(IIS和PHP Web服务器都有免费版本,它们可以在本地计算机上正常运行)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM