使用JavaScript将画布转换为图像 [英] Convert canvas to an image with JavaScript
问题描述
我想使用JavaScript将画布转换为图像,当我尝试 canvas.toDataURL(image / png);
时会出现错误 SecurityError:操作不安全
。请帮我解决这个问题。
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.
提前致谢。
推荐答案
你有正确的想法,它将在非常简单的情况下工作,例如:
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/
但是如果你的画布弄脏了就会出现问题。这是通过将图像绘制到来自不同来源的画布来完成的。例如,如果您的画布在www.example.com上托管,并且您使用来自www.wikipedia.org的图像,那么您的画布'origin-clean标志设置为 false
内部。
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.
将origin-clean标志设置为 false
后,您将不再被允许致电 toDataURL
或 getImageData
Once the origin-clean flag is set to false
, you are no longer allowed to call toDataURL
or getImageData
从技术上讲,如果域,协议和端口匹配,图像的来源相同。
Technically, images are of the same origin if domains, protocols, and ports match.
如果你是在本地工作(文件://)然后绘制的任何图像将引发该标志。这会使调试变得烦人,但使用Chrome,您可以使用标志 - allow-file-access-from-files
启动它以允许调试。
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.
这篇关于使用JavaScript将画布转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!