The content of this article is to introduce how to call the camera with js? js method to call the camera (detailed code explanation). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
For details, please see: https://github.com/ProsperLe
<div> <b>调用移动端摄像头</b><br> <label>照相机: <input type="file" id='image' accept="image/*" capture='camera'></label> <label>摄像机: <input type="file" id='video' accept="video/*" capture='camcorder'></label> </div> <hr> <div class="box1"> <div> <button onclick="getMedia()">开启摄像头</button> <video id="video" width="600" height="400" autoplay="autoplay"></video> </div> <div> <button onclick="takePhoto()">拍照</button> <canvas id="canvas" width="600" height="400"></canvas> </div> </div> <script> function getMedia() { let constraints = { video: { width: 600, height: 400 }, 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) { /* 使用这个MediaStream */ video.srcObject = MediaStream; video.play(); console.log(MediaStream); // 对象 }) // 失败调用 promise.catch(function (err) { /* 处理error */ console.log(err); // 拒签 }); } function takePhoto() { //获得Canvas对象 let video = document.getElementById("video"); let canvas = document.getElementById("canvas"); let ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, 600, 400); } </script>
The above is the detailed content of How to call the camera with js? js method to call camera (detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!