1. 程式人生 > 其它 >js調取攝像頭拍照

js調取攝像頭拍照

<!DOCTYPE html> <html lang="zh">
<head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>拍照</title> </head>
<body>     <button onclick="openMedia()" >開啟攝像頭</button>     <button onclick="takePhoto()" >拍照</button><br/><br/>     <video style="display: none;" class="src-video" width="300px" height="300px" autoplay="autoplay"></video>     <canvas id="canvas" width="300px" height="300px" style="display: none;"></canvas>     <img src="" alt="" class="photo"> </body> <script>     let srcVideo = document.querySelector('video.src-video');     let mediaStream;     let photo=document.querySelector('img.photo');     // 開啟攝像頭     let openMedia = function () {         photo.src='';         srcVideo.style.display='block';         let constraints = {             audio: false, //音訊軌道             video: {width:300,height:300}  //視訊軌道         }         let mediaPromise = navigator.mediaDevices.getUserMedia(constraints);         mediaPromise.then(function (stream) {             /* 使用這個stream stream */             mediaStream=stream;             srcVideo.srcObject = stream;             srcVideo.play();         }).catch(function (err) {             /* 處理error */             alert(err);         });     };
    // 拍照     let takePhoto=function(){         let canvas = document.querySelector('#canvas');         //獲取 `canvas`元素,根據`srcVideo`中的資料進行圖片繪製 `ctx.drawImage()`;         let ctx = canvas.getContext('2d');         ctx.drawImage(srcVideo, 0, 0, 300, 300);         //將 `canvas`繪製的圖片資訊,展示在 `img`標籤中;         photo.src=canvas.toDataURL();     console.log(photo.src);     // 方式1     // base64轉blob     const blob = base64ToBlob(base64Data);     // blob轉file     const file1 = blobToFile(blob, '檔名');
    // 方式2     // base64轉file     const file2 = base64ToFile(base64Data, '檔名');         closeMedia();     };
    // 關閉攝像頭     let closeMedia=function(){         mediaStream.getTracks().forEach(track => {             track.stop();         });         srcVideo.style.display='none';     };     function base64ToFile(base64Data, fileName) {     let arr = base64Data.split(','),       fileType = arr[0].match(/:(.*?);/)[1],       bstr = atob(arr[1]),       l = bstr.length,       u8Arr = new Uint8Array(l);
    while (l--) {       u8Arr[l] = bstr.charCodeAt(l);     }     return new File([u8Arr], fileName, {type: fileType});   }  
</script> </html>