前端調用攝像頭並且實現拍照功能


<!DOCTYPE html>

< html >
< head >
     < title >Photo</ title >
         < style >
             video {transform: rotateY(180deg);}
         </ style >
</ head >
< body >
     < button  onclick="showCamera()">開啟攝像頭</ button >
     < div  class="bg-content" style="display: none;">
         < div  class="show-photo">
             < video  id="video" width="600px" height="600px" autoplay="autoplay"></ video >
             < canvas  id="canvas" width="600px" height="600px" style="display: none;"></ canvas >
             < a  id="downloadA"></ a >
         </ div >
         < div  class="take-photo">
             < button  type="button" onclick="takePhoto()">
                 拍照
             </ button >
         </ div >
         < div  class="close-photo">
             < button  type="button" onclick="closePhoto()">
                 關閉
             </ button >
         </ div >
     </ div >
 
     < script  type="text/javascript">
         /**
          * 開啟攝像頭
          */
         let mediaStreamTrack = null; // 視頻對象(全局)
         function showCamera() {
             $(".bg-content").css("display", "block");
             let constraints = {
                 video: {width: 600, height: 600},
                 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) {
                 mediaStreamTrack = typeof MediaStream.stop === 'function' ? MediaStream : MediaStream.getTracks()[1];
                 video.srcObject = MediaStream;
                 video.muted = true;
                 video.play();
             });
         }
 
         /**
          * 拍攝照片
          */
         function takePhoto() {
             let video = document.getElementById("video");
             let canvas = document.getElementById("canvas");
             let ctx = canvas.getContext('2d');
             ctx.drawImage(video, 0,
             ctx.translate(canvas.width, 0);
             ctx.scale(-1, 1);、
             let img = document.getElementById("canvas").toDataURL("image/png");
             var triggerDownload = $("#downloadA").attr("href", img).attr("download", "micro-blog.png");
             triggerDownload[0].click();
         }
 
         /**
          * 關閉攝像頭
          */
         function closePhoto() {
             mediaStreamTrack.stop();
             $(".bg-content").css("display", "none");
         }
     </ script >
</ body >
</ html >


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM