在HTML里加载摄像头的方法
(编辑:jimmy 日期: 2024/11/24 浏览:3 次 )
效果图: 整体效果:
视频加载:
拍照:
第一步:创建HTML元素
首先,我们要创建一个HTML5的文档。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> </body> </html>
然后在<body></body>
插入以下代码:
<video id="video" width="640" height="480" autoplay></video> <button id="snap">截图</button> <canvas id="canvas" width="640" height="480"></canvas>
第二步:创建JavaScript
首先,要在<head></head>
里创建一个JavaScript:
<script language="javascript"> // Grab elements, create settings, etc. var video = document.getElementById('video'); // Get access to the camera! if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { // Not adding `{ audio: true }` since we only want video now navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } /* Legacy code below: getUserMedia else if(navigator.getUserMedia) { // Standard navigator.getUserMedia({ video: true }, function(stream) { video.src = stream; video.play(); }, errBack); } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed navigator.webkitGetUserMedia({ video: true }, function(stream){ video.src = window.webkitURL.createObjectURL(stream); video.play(); }, errBack); } else if(navigator.mozGetUserMedia) { // Mozilla-prefixed navigator.mozGetUserMedia({ video: true }, function(stream){ video.srcObject = stream; video.play(); }, errBack); } */ </script>
随后,要在刚才创建的HTML元素的后面插入以下代码:
<script language="javascript"> // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var video = document.getElementById('video'); // Trigger photo take document.getElementById("snap").addEventListener("click", function() { context.drawImage(video, 0, 0, 640, 480); }); </script>
现在,这个HTML就可以完成打开摄像头,和拍照的功能了!
下一篇:详解html-webpack-plugin使用