
詳情源碼請參見下方的 GitHub !!!
1 <div> 2 <b>調用移動端攝像頭</b><br> 3 <label>照相機: <input type="file" id='image' accept="image/*" capture='camera'></label> 4 <label>攝像機: <input type="file" id='video' accept="video/*" capture='camcorder'></label> 5 </div> 6 <hr> 7 <div class="box1"> 8 <div> 9 <button onclick="getMedia()">開啟攝像頭</button> 10 <video id="video" width="600" height="400" autoplay="autoplay"></video> 11 </div> 12 <div> 13 <button onclick="takePhoto()">拍照</button> 14 <canvas id="canvas" width="600" height="400"></canvas> 15 </div> 16 </div> 17 <script> 18 function getMedia() { 19 let constraints = { 20 video: { 21 width: 600, 22 height: 400 23 }, 24 audio: true 25 }; 26 //獲得video攝像頭區域 27 let video = document.getElementById("video"); 28 29 // 這里介紹新的方法,返回一個 Promise對象 30 // 這個Promise對象返回成功后的回調函數帶一個 MediaStream 對象作為其參數 31 // then()是Promise對象里的方法 32 // then()方法是異步執行,當then()前的方法執行完后再執行then()內部的程序 33 34 // 避免數據沒有獲取到 35 let promise = navigator.mediaDevices.getUserMedia(constraints); 36 // 成功調用 37 promise.then(function (MediaStream) { 38 /* 使用這個MediaStream */ 39 video.srcObject = MediaStream; 40 video.play(); 41 console.log(MediaStream); // 對象 42 }) 43 // 失敗調用 44 promise.catch(function (err) { 45 /* 處理error */ 46 console.log(err); // 拒簽 47 }); 48 } 49 50 function takePhoto() { 51 //獲得Canvas對象 52 let video = document.getElementById("video"); 53 let canvas = document.getElementById("canvas"); 54 let ctx = canvas.getContext('2d'); 55 ctx.drawImage(video, 0, 0, 600, 400); 56 } 57 </script>
