首先我们需要新建一个video标签,并且放到html里边
var video = document.createElement("video");
video.autoplay="autoplay";
document.body.appendChild(video);
利用navigator对象
navigator.mediaDevices.getUserMedia({ audio:true, video:true })
这样就调用了摄像头和录音器
navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(function (result) { video.srcObject = result; })
利用video的srcObject属性和promise的then方法,把开启摄像头后的返回值给video标签,就显示出来了
全部的实现代码如下:
var video = document.createElement("video"); video.autoplay="autoplay"; document.body.appendChild(video); navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(function (result) { video.srcObject = result; })
现在我们继续写canvas拍照的步骤
<video id='myVideo' hidden></video> <canvas id='snap' width='500' height='500' style="border:1px solid #ccc"></canvas> <button id='control'>拍照</button> <script> var snap = document.getElementById('snap'); var context = snap.getContext('2d'); var videoSrc = null; navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(function (result) { videoSrc = result; console.log(videoSrc) myVideo.srcObject = videoSrc; }) control.addEventListener('click',function(){ context.drawImage(myVideo,0,0,500,500); console.log(navigator.mediaDevices) }) </script>
新建canvas画布,获得context
隐藏video
canvas.drawImage方法的第一个参数放video即可调用canvas拍照