<input type="button" title="開啓攝像頭" value="開啓攝像頭" onclick="getMedia()" />canvas
<video id="video" width="500px" height="500px" autoplay="autoplay"></video> <canvas id="canvas" width="500px" height="500px"></canvas> <button id="snap" onclick="takePhoto()">拍照</button>
function getMedia() {promise
let constraints = { video: {width: 500, height: 500}, audio: true }; //得到video攝像頭區域 let video = document.getElementById("video"); //這裏介紹新的方法,返回一個 Promise對象 // 這個Promise對象返回成功後的回調函數帶一個 MediaStream 對象做爲其參數 // then()是Promise對象裏的方法 // then()方法是異步執行,當then()前的方法執行完後再執行then()內部的程序 // 避免數據沒有獲取到 let promise = navigator.mediaDevices.getUserMedia(constraints); promise.then(function (MediaStream) { video.srcObject = MediaStream; video.play(); }); }
function takePhoto() {異步
//得到Canvas對象 let video = document.getElementById("video"); let canvas = document.getElementById("canvas"); let ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, 500, 500); } 來源:CSDN