基於html5 JS實現的拍照上傳圖片
阿新 • • 發佈:2019-01-04
<style> #video,#canvas {display: block;margin:1em auto;width:180px;height:180px;} #snap { display: block;margin:0 auto;width:80%;height:2em; } </style> <div class="container"> <video id="video" autoplay></video> <button id="snap">點選拍照</button> <canvas id="canvas"></canvas> </div> <script> window.addEventListener("DOMContentLoaded", function () { try { document.createElement("canvas").getContext("2d"); } catch (e) { alert("not support canvas!") } var video = document.getElementById("video"), canvas = document.getElementById("canvas"), context = canvas.getContext("2d"); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; if (navigator.getUserMedia) navigator.getUserMedia( { "video": true }, function (stream) { if (video.mozSrcObject !== undefined)video.mozSrcObject = stream; else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream; video.play(); }, function (error) { //if(error.PERMISSION_DENIED)console.log("使用者拒絕了瀏覽器請求媒體的許可權",error.code); //if(error.NOT_SUPPORTED_ERROR)console.log("當前瀏覽器不支援拍照功能",error.code); //if(error.MANDATORY_UNSATISFIED_ERROR)console.log("指定的媒體型別未接收到媒體流",error.code); alert("Video capture error: " + error.code); } ); else alert("Native device media streaming (getUserMedia) not supported in this browser"); $('#snap').on('click', function () { context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight); $.post('/home/index', { "img": canvas.toDataURL().substr(22) }, function (data, status) { alert(status!="success"?"圖片處理出錯!":data== "yes"?"圖片上傳完成!":data); }, "text"); }); }, false); </script>