H5调用本地摄像头拍摄照片

前言

最近项目中需要H5调用本地摄像头拍照的需求。

代码

<canvas id="canvasCemara" width="500" height="500"></canvas>
<video autoplay="" id="video2" style="width:500px;height:500px;"></video>
<button id="btn">拍摄</button>

html 部分就这些 一个canvas 一个 video  一个button 
video  展示摄像头捕获的视频
canvas 负责展示拍摄的照片

var video = document.getElementById('video2');
var constraints = {audio: false, video: true};
 function successCallback(stream) {
     video.srcObject = stream;
     video.play();
 }
 function errorCallback(error) {
     console.log("navigator.getUserMedia error: ", error);
     $(".CameraTips").show();
 }

 navigator.mediaDevices.getUserMedia(constraints)
     .then(successCallback)
     .catch(errorCallback);

document.getElementById("btn").addEventListener("click", function () {
    var video = document.getElementById('video2');
    canvas = document.getElementById('canvasCemara');
    ctx = canvas.getContext('2d');
    var _w = 624, _h = 468;
    if (video.videoWidth > 0) _h = video.videoHeight / (video.videoWidth / _w);
    canvas.setAttribute('width', _w);
    canvas.setAttribute('height', _h);
    ctx.fillRect(0, 0, _w, _h);
    ctx.drawImage(video, 0, 0, _w, _h);
});

按下btn 将视频中的内容画在canvas里面 完成拍摄效果。

猜你喜欢

转载自blog.csdn.net/merciwen/article/details/78858068