js vue 在页面中将摄像头放在一个标签里展示,(模仿手机拍照功能)
1.HTML
<video id="video" autoplay class="fileImg"></video> <canvas id="canvas" width="640" height="480"></canvas>
<div class="submitButton buttonData" @click="uploadImg">上传图片</div>
2.JS
<script> let aVideo = document.getElementById('video'); let aCanvas = document.getElementById('canvas'); let ctx = aCanvas.getContext('2d'); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; //获取媒体对象(这里指摄像头) navigator.getUserMedia({ video: true }, gotStream, noStream); //参数1获取用户打开权限;参数二成功打开后调用,并传一个视频流对象,参数三打开失败后调用,传错误信息 function gotStream(stream) { video.src = URL.createObjectURL(stream); video.onerror = function() { stream.stop(); }; stream.onended = noStream; video.onloadedmetadata = function() { // alert('摄像头成功打开!'); }; } function noStream(err) { // alert(err); } function uploadImg(){ ctx.drawImage(aVideo, 0, 0, 640, 480); alert(aCanvas.toDataURL('image/png')) // 得到base64,需要后台将base64转换并上传到服务器,返回线上http路径 const res = await fileUpload({imgStr: aCanvas.toDataURL('image/png')}) // 调取后台接口 if (res.data.code == 0){ this.headImage = res.data.data.string //得到后台返回路径 } } </script>