使用JavaScript从网络摄像头捕获图像,而无需页面刷新
Capture image from webcam with JavaScript without page refresh
我创建了HTML表单,其中一个字段是一个canvas
div,它从用户的网络摄像头中获取图像并将其保存为base64_encode,目前只是console.log()
数据。问题是,每次用户按下"拍照"按钮后,页面刷新和之前输入中填写的所有数据都会消失/删除。我一直试图忍受导致这种刷新的原因,但无法弄清楚......
这是相关的 HTML 部分:
<div class="form-group">
<input minlength=8 type="password" class="form-control" name="pass" placeholder="Enter Password" required/>
</div>
<div class="form-group">
<div id="camera">
<div class="center clear">
<video id="video" width="320" height="240" autoplay></video>
<button id="snap">Take Picture</button>
<canvas id="canvas" width="320" height="240"></canvas>
</div>
</div>
和JS:
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 320, 240);
var image = document.getElementById("canvas");
var pngUrl = canvas.toDataURL();
console.log(pngUrl);
});
}, false);
知道为什么单击<button id="snap">Take Picture</button>
刷新页面以及如何防止它吗? 谢谢
如果您在<form>
中有<button>
,则默认情况下单击它将提交表单。若要防止出现这种情况,可以使用event.preventDefault
停止提交。
var form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
}, true);
万一其他人遇到这个问题,我设法使用 @Mike C 的指导解决了这个问题......我只是将其添加到button
:
<button id="snap" onclick="return false;">Take Picture</button>
相关文章:
- Jquery在源更改后刷新图像
- Javascript图像刷新
- 如何在javaservlet中通过javascript刷新图像
- 如何在提交后关闭颜色框窗口,并刷新父页面上的图像
- 在Div中刷新图像,只更改文件内容,不更改名称
- 如何仅在新图像实际可用时刷新图像源
- 使用setInterval()刷新图像
- 在 php 应用程序中自动刷新图像
- iOS 上的 Safari 中的刷新图像
- 刷新图像在 Mozilla 中不起作用
- 使用JQuery或Javascript刷新图像
- 单击按钮刷新图像,不刷新页面
- JQuery Onclick Change Image Src未刷新图像
- 使用Javascript加载刷新图像
- Javascript用于使用VS2010刷新图像
- Javascript和ASP MVC -刷新图像
- 当文本改变时,刷新图像
- 刷新图像从外部URL点击
- 使用jquery更改媒体刷新图像大小
- 用base64修改src后刷新图像元素