javascript实现摄像头拍照预览
使用javascript实现电脑摄像头的打开和截图的功能,供大家参考,具体内容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>摄像头调用实例</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var video, mediaStreamTrack, canvas;//声明全局变量
//打开摄像头
function dk() {
video = document.getElementById("v1");
var videoObj = {
"video" : true
};
var errBack = function(error) {
console.log("Video capture error: ", error.code);
};
//根据浏览器的不同选取不同的支持
if (navigator.getUserMedia) { // Standarda
navigator.getUserMedia(videoObj, function(stream) {
mediaStreamTrack = typeof stream.stop === 'function' ? stream
: stream.getTracks()[1];
video.src = stream;//获取摄像头抓取的到字节流
video.play();//实时播放摄像头
}, errBack);
} else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream) {
mediaStreamTrack = typeof stream.stop === 'function' ? stream
: stream.getTracks()[1];
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if (navigator.mozGetUserMedia) { // Firefox-prefixed
navigator.mozGetUserMedia(videoObj, function(stream) {
mediaStreamTrack = typeof stream.stop === 'function' ? stream
: stream.getTracks()[1];
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
}
//截图
function jq() {
canvas = document.getElementById("c1");
var context = canvas.getContext("2d");
//将视频当前的页面转换为图片,显示到画板中
context.drawImage(video, 0, 0, 200, 202);
//把canvas图像转为img图片
/* var src = canvas.toDataURL("image/jpeg");
createImg(src); */
}
//关闭摄像头
function gb() {
mediaStreamTrack.stop();
}
//生成图片
/* function createImg(src) {
var dv = document.getElementById("dv1");
var img = document.createElement("img");
img.setAttribute("src", src);
img.setAttribute("width", 205);
img.setAttribute("height", 205);
dv.appendChild(img);
} */
//上传
/* function sc() {
$.post('TestServlet', {
"img" : canvas.toDataURL().substr(22)
}, function(data, status) {
alert(status != "success" ? "图片处理出错!" : data == "yes" ? "图片上传完成!"
: data);
});
} */
</script>
<style type="text/css">
input[type="button"]{
border: 1px solid red;
}
</style>
</head>
<body>
<div>
<input type="button" value="打开" onclick="dk()">
<input type="button" value="截取图像" onclick="jq()">
<input type="button" value="关闭" onclick="gb()">
</div>
<div>
<!--视频 -->
<video width="200px" height="200px" id="v1"></video>
<br />
<!--画板 -->
<canvas id="c1"></canvas>
<br />
</div>
<!--记录每次截图的结果 -->
<!-- <div id="dv1"></div> -->
</body>
</html>
但是谷歌浏览器可以打开摄像头,无法获取实时数据。火狐比较好用。
以上是 javascript实现摄像头拍照预览 的全部内容, 来源链接: utcz.com/z/336177.html