1. 程式人生 > >H5呼叫本地攝像頭

H5呼叫本地攝像頭

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://123.56.106.187:8010/Scripts/listjs/jquery-1.7.2.min.js"></script>
<script>
//判斷瀏覽器是否支援HTML5 Canvas
window.onload = function () {
try {
//動態建立一個canvas元 ,並獲取他2Dcontext。如果出現異常則表示不支援 document.createElement("canvas").getContext("2d");
// document.getElementById("support").innerHTML = "瀏覽器支援HTML5 CANVAS";
}
catch (e) {
// document.getElementByIdx("support").innerHTML = "瀏覽器不支援HTML5 CANVAS";
}
};
//這段代 主要是獲取攝像頭的視訊流並顯示在Video 籤中
window.addEventListener("DOMContentLoaded", function () {
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);
};
$("#snap").click(function () {
context.drawImage(video, 0, 0, 330, 250);
})
//navigator.getUserMedia這個寫法在Opera中好像是navigator.getUserMedianow
if (navigator.getUserMedia) {
navigator.getUserMedia(videoObj, function (stream) {
video.src = stream;
video.play();
}, errBack);
} else if (navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia(videoObj, function (stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}

}, false);

//上傳伺服器
function CatchCode() {
var canvans = document.getElementById("canvas");
//獲取瀏覽器頁面的畫布物件
//以下開始編 資料
var imgData = canvans.toDataURL();
//將影象轉換為base64資料
var base64Data = imgData.substr(22);
//在前端擷取22位之後的字串作為影象資料
//開始非同步上
$.post("uploadImgCode.ashx", { "img": base64Data }, function (data, status) {
if (status == "success") {
if (data == "OK") {
alert("二維 已經解析");
}
else {
// alert(data);
}
}
else {
alert("資料上 失敗");
}
}, "text");
}
</script>
</head>
<body>
<div id="contentHolder">
<video id="video" width="320" height="320" autoplay>
</video>
<input type="button" id="snap" style="width:100px;height:35px;" value="拍 照" />
<canvas style="" id="canvas" width="320" height="320">
</canvas>
</div>
</body>
</html>