使用js調用攝像頭拍照

在一些瀏覽器裏已經可使用web api調用攝像頭功能了。
基於此能夠經行拍照攝像功能,網上找了些資料,而後實現了簡單的拍照功能
演示地址 bingxl.cn/webrtc.htmlhtml

代碼git

<!DOCTYPE html>
<html lang="ZH-CN">
<head>
  <meta charset="utf-8">
  <title>web RTC 測試</title>
  <style>
    .booth {
      width:400px;
     
      background:#ccc;
      border: 10px solid #ddd;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <div class="booth">
    <video id="video" width="400" height="300"></video>
    <button id='tack'> snap shot</button>
    <canvas id='canvas' width='400' height='300'></canvas>
    <img id='img' src=''>
  </div>
 
 
  <script>
    var video = document.getElementById('video'),
        canvas = document.getElementById('canvas'),
        snap = document.getElementById('tack'),
        img = document.getElementById('img'),
        vendorUrl = window.URL || window.webkitURL;
        
    //媒體對象
    navigator.getMedia = navigator.getUserMedia ||
                         navagator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia;
    navigator.getMedia({
        video: true, //使用攝像頭對象
        audio: false  //不適用音頻
    }, function(strem){
        console.log(strem);
        video.src = vendorUrl.createObjectURL(strem);
        video.play();
    }, function(error) {
        //error.code
        console.log(error);
    });
    snap.addEventListener('click', function(){
    
        //繪製canvas圖形
        canvas.getContext('2d').drawImage(video, 0, 0, 400, 300);
        
        //把canvas圖像轉爲img圖片
        img.src = canvas.toDataURL("image/png");
        
    })
  </script>
</body>
</html>

demo演示;github

特別說明web

  1. 有些瀏覽器可能不支持此功能
  2. 必須經過服務器打開頁面,經過files://打開無效
  3. 若是經過遠程服務器打開則必須是https協議, http協議也沒法使用
相關文章
相關標籤/搜索