H5實現拍照並上傳


<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta content="telephone=no" name="format-detection" />
    <title>測試</title>
</head>
<body>
<video id="video" width="320" height="240" autoplay></video>
<button id="snap">拍攝</button>
<canvas id="canvas" width="320" height="240"></canvas>
<script>
    window.addEventListener("DOMContentLoaded", function() {
        var canvas = document.getElementById("canvas"),//調用canvas接口
                context = canvas.getContext("2d"),
                video = document.getElementById("video"),
                videoObj = { "video": true },
                errBack = function(error) {//錯誤處理
                    console.log("Video capture error: ", error.code);
                };
        if(navigator.getUserMedia) {//調用html5拍攝接口
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;//攝像機屬於視頻流,所以當然要輸出到html5的video標簽中了
                video.play();//開始播放
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { //WebKit內核調用html5拍攝接口
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);//同上
                video.play();//同上
            }, errBack);
        }
        else if(navigator.mozGetUserMedia) { //moz內核調用html5拍攝接口
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);//同上
                video.play();//同上
            }, errBack);
        }
    }, false);

    document.getElementById("snap")
            .addEventListener("click", function() {//獲取拍照按鈕綁定事件
                var canvans = document.getElementById("canvas"),//調用canvas接口
                        context = canvas.getContext("2d");
                context.drawImage(video, 0, 0, 640, 480);//調用canvas接口的drawImage方法繪制當前video標簽中的靜態圖片,其實就是截圖

                var imgData = canvans.toDataURL();//獲取圖片的base64格式的數據
                //這里就可以寫上傳服務器代碼了
            });
</script>
</body>
</html>


免責聲明!

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



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