javascript 如何从画布中保存图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18480474/
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
How to save an image from canvas
提问by user2724072
Recently I've been attempting to create a photo booth by relying on Webrtc and have nearly completed all of the code except I've not been able to figure out a way to save the image after it has been captured.
最近我一直在尝试依靠 Webrtc 创建一个照相亭,并且几乎完成了所有代码,只是我无法找到一种在捕获图像后保存图像的方法。
This is the closest I've come so far to achieving my goal:
这是迄今为止我最接近实现目标的方法:
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>fotogoof</title>
<link rel="Stylesheet" href="css/bootstrap.css"/>
<link rel="Stylesheet" href="css/style.css"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('screenshot');
var button = document.getElementById('saveImage');
img.src = '';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<h2 class="brand">Html5 Photobooth</h1>
</div>
</div>
</div>
<div class="container" id="body-wrap">
<div class="container" id="main">
<div class="span10">
<div id="video-container">
<canvas width="400" height="320" class="mask"></canvas>
<div id="counter">
</div>
</div>
<br><div id="pic-holder" class="pull-left"><img id="screenshot"></div></br>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</div>
</div>
</div>
</div>
The code is essentially taking the webcam stream and feeding it into a canvas element. Pressing the space button triggers a screenshot to be taken, which then appears as an image. Because I'm unable to provide the exact source of the file that is being downloaded the button only opens the image in another tab in the browser instead of functioning properly. I would really appreciate some input as to how I can resolve this. Thanks in advance.
该代码本质上是获取网络摄像头流并将其输入到画布元素中。按空格键会触发截屏,然后显示为图像。因为我无法提供正在下载的文件的确切来源,所以按钮只会在浏览器的另一个选项卡中打开图像,而不是正常运行。我真的很感激一些关于如何解决这个问题的意见。提前致谢。
I've already managed to do capture the stream from the canvas in an image with this bit of code:
我已经设法使用以下代码从画布中的图像中捕获流:
document.addEventListener ('keydown', function (event) {
if(event.keyCode == 32) {
document.querySelector('#screenshot').src = canvas.toDataURL('image/webp')
}
})
What I want to know is how to enable the user to save the image onto their computer from there.
我想知道的是如何使用户能够从那里将图像保存到他们的计算机上。
回答by
If I understand correctly you want to download (ie. provide a save dialog for the user to pick a location) the image to user's machine?'
如果我理解正确,您想将图像下载(即提供一个保存对话框供用户选择位置)到用户的机器上?
If so you can use this snippet:
如果是这样,您可以使用此代码段:
function download(canvas, filename) {
/// create an "off-screen" anchor tag
var lnk = document.createElement('a'),
e;
/// the key here is to set the download attribute of the a tag
lnk.download = filename;
/// convert canvas content to data-uri for link. When download
/// attribute is set the content pointed to by link will be
/// pushed as "download" in HTML5 capable browsers
lnk.href = c.toDataURL();
/// create a "fake" click-event to trigger the download
if (document.createEvent) {
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
lnk.dispatchEvent(e);
} else if (lnk.fireEvent) {
lnk.fireEvent("onclick");
}
}
Now all you need to do is to provide a default file name and call the function:
现在您需要做的就是提供一个默认文件名并调用该函数:
download(myCanvas, 'untitled.png');
If you rather than this mean save directlyto user's harddisk then you can't due to security reasons.
如果你不是这意味着直接保存到用户的硬盘,那么出于安全原因你不能。
That being said, there is always the option of using local storage such as File API or Indexed DB - but as these are sand-boxed you and the user will only have access to the "files" through the browser so perhaps not so convenient.
话虽如此,始终可以选择使用本地存储,例如文件 API 或索引数据库 - 但由于这些是沙盒化的,您和用户只能通过浏览器访问“文件”,因此可能不太方便。
回答by PEZ
I don't think it's possible for IE without involving a server side script. Here's a good writeup on how to do it that way.
我认为 IE 不涉及服务器端脚本是不可能的。这是一篇关于如何做到这一点的好文章。
回答by Plcode
I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:
我遇到了这个问题,这是最好的解决方案,没有任何外部或额外的脚本库:在 Javascript 标签或文件中创建这个函数:我们在这里假设画布是你的画布:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
在 HTML 的正文部分指定按钮:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button.
这是有效的,下载链接看起来像一个按钮。
回答by Roy M J
Regarding the first task, you can export the canvas content to an image with toDataUrl method supported by the canvas object.
关于第一个任务,您可以使用画布对象支持的 toDataUrl 方法将画布内容导出为图像。
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d"); // Get the context for the canvas.
var myImage = canvas.toDataURL("image/png"); // Get the data as an image.
}
var image = document.getElementById("screenshot"); // Get the image object.
image.src = myImage;