jQuery 使用 JavaScript 将画布转换为图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16301449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert canvas to an image with JavaScript
提问by mmpatel009
I want to convert canvas to an image with JavaScript, When i try to canvas.toDataURL("image/png");
it gives error SecurityError: The operation is insecure
. Please help me to solve this probmen.
我想使用 JavaScript 将画布转换为图像,当我尝试canvas.toDataURL("image/png");
它时会出现错误SecurityError: The operation is insecure
。请帮我解决这个问题。
Thanks in advance.
提前致谢。
回答by Simon Sarris
You have the right idea, and it will work in very simple cases such as:
您的想法是正确的,它适用于非常简单的情况,例如:
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
http://jsfiddle.net/simonsarris/vgmFN/
http://jsfiddle.net/simonsarris/vgmFN/
But it becomes problematic if you have "dirtied" your canvas. This is done by drawing images to the canvas that are from a different origin. For instance, if your canvas is hosted at www.example.com, and you use images from www.wikipedia.org, then your canvas' origin-clean flag is set to false
internally.
但是,如果您“弄脏”了画布,就会出现问题。这是通过将来自不同来源的图像绘制到画布上来完成的。例如,如果您的画布托管在 www.example.com,并且您使用来自 www.wikipedia.org 的图像,则您的画布的 origin-clean 标志设置为false
内部。
Once the origin-clean flag is set to false
, you are no longer allowed to call toDataURL
or getImageData
一旦 origin-clean 标志设置为false
,您就不能再调用toDataURL
或getImageData
Technically, images are of the same origin if domains, protocols, and ports match.
从技术上讲,如果域、协议和端口匹配,则图像具有相同的来源。
If you are working locally (file://) then any image drawn will set off the flag. This makes debugging annoying, but with Chrome you can start it with the flag --allow-file-access-from-files
to allow this.
如果您在本地工作 (file://),那么绘制的任何图像都会引发该标志。这让调试变得烦人,但是在 Chrome 中,您可以使用标志--allow-file-access-from-files
来启动它以允许这样做。
回答by Sharan Rajendran
This worked for me
这对我有用
//after creating your plot do
var imgData = $('#chart1').jqplotToImageStr({}); // given the div id of your plot, get the img data
var imgElem = $('<img/>').attr('src',imgData); // create an img and add the data to it
$('#imgChart1').append(imgElem);?????????????????????????????????????????????????? //