HTML5实现按键打开摄像头和拍照

步骤:

1、创建一个打开摄像头按钮的标签、video标签、拍照的按钮标签、画布

2、实现打开摄像头的功能

3、实现拍照功能

 

具体实现代码:

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>takePhoto</title>
   <script type="text/javascript">
     window.addEventListener("DOMContentLoaded",function(){
     var drawing = document.getElementById("drawing");
       if(drawing.getContext)
      {
        context = drawing.getContext("2d");
      }
     var video = document.getElementById("video");
     var med = {video:true};
     var errBack = function(e)
     {
       alert("An error has occurred",e)
     }
     var onCamera = document.getElementById("onCamera");
     var takePhoto = document.getElementById("takePhoto")

     //实现通过按钮打开摄像头的功能
     onCamera.addEventListener("click",function(){
     f(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
     {
       navigator.mediaDevices.getUserMedia(med).then(function(stream){
       video.src = window.URL.createObjectURL(stream);
       video.play();
     })
    console.log(navigator.mediaDevices.getUserMedia(med))
    }
    },false);
    //实现将拍照功能
    takePhoto.addEventListener("click",function(stream){
    context.drawImage(video,0,0,640,480)
    },false);
    },false)
    </script>
  </head>
  <body>
    <button id="onCamera">打开摄像头</button>
    <video id="video" width="640" height="480"></video>
    <button id="takePhoto">拍照</button>
    <canvas id="drawing" width="640" height="480">A drawing of something</canvas>
</body>
</html>

 

 

05-07 10:32