瀏覽器呼叫攝像頭進行拍照程式

Jouzeyu發表於2020-03-16
 <div style="width: 100%;height: 490px;">
        <div id="phone">
            <video id="video" width="480" height="360" autoplay></video>
        </div>
        <div class="showphone">
            <canvas id="canvas" width="480" height="360"></canvas> 
        </div>
 </div>
 <div>
     <form method="post" id="formsrc" enctype="multipart/form-data">
    <input type="hidden" value="" id="imgsrc" name="imgsrc">
    </form>
    <button id="snap">點選驗證</button>
 </div>

js程式碼部分

    <script type="text/javascript">
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        var video = document.getElementById("video");
        var imgsrc = document.getElementById("imgsrc");
        $(document).ready(function() {
            videoObj = {
                "video": true
            };
            var errBack = function(error) {
                console.log("Video capture error: ", error.code);
            };
            if (navigator.getUserMedia) { // Standard
                navigator.getUserMedia(videoObj, function(stream) {
                    video.srcObject = stream;
                    video.play();
                }, errBack);
            } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
                navigator.webkitGetUserMedia(videoObj, function(stream) {
                    video.src = window.webkitURL.createObjectURL(stream);
                    video.play();
                }, errBack);
            } else if (navigator.mozGetUserMedia) { // Firefox-prefixed
                navigator.mozGetUserMedia(videoObj, function(stream) {
                    video.src = window.URL.createObjectURL(stream);
                    video.play();
                }, errBack);
            };
            $("#snap").on("click", function() {
                context.drawImage(video, 0, 0, 480, 360);
                // console.log(canvas.toDataURL('jpg'))
                var sr=canvas.toDataURL('jpg');
                var src= sr.replace(/^data:image\/\w+;base64,/, "");
                imgsrc.value=src;
                staticTest(src);
            });
        });
    </script>

簡單說一下,因為時間很緊的緣故。這段程式碼是去年忘記什麼時候嘗試寫的一個基於瀏覽器的人臉識別的專案,遺憾的是因為某些缺陷沒有進行到最後,不過這塊可以拆分下來,留作紀念。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

空舟湖上~
     ——Jouzeyu

相關文章