纯前端实现(摄像头)截屏
navigator-helper.js
// 获取媒体设备 export const getUserMedia = () => { return new Promise((resolve,reject) => { navigator.getUserMedia({ audio: true, video: true }, (stream) => { resolve(stream) },(e)=>{ reject(e) }) }) } // 将视频转为base64图片 export const screenCapture = (video)=>{ const canvas = document.createElement("canvas"); const canvasCtx = canvas.getContext("2d"); canvas.width = 360; canvas.height = 240; canvasCtx.drawImage(video, 0, 0, canvas.width, canvas.height); return canvas.toDataURL("image/png"); }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .action div{background-color: pink; padding: 10px; cursor: pointer; color: white; margin: 10px 0; display: inline-block;} .screen-capture{visibility: hidden;} img{margin-right: 10px;} </style> </head> <body> <div class="action"> <div class="open-video ">开/关闭摄像头</div> <div class="screen-capture">截屏</div> </div> <video autoplay playsinline></video> <div class="show-img"></div> <script type="module"> import {getUserMedia, screenCapture} from './navigator-helper.js'; const openVideoEl = document.querySelector('.open-video');// 打开摄像头按钮 let localMediaStream = null; //本地多媒体工具,如摄像头或者麦克风(流) const screenCaptureEl = document.querySelector('.screen-capture'); // 截屏按钮 const videoEl = document.querySelector('video');// 视频框 // 打开摄像头点击事件 openVideoEl.onclick = async function(){ // 关闭摄像头、隐藏截屏按钮 if(localMediaStream){ localMediaStream.getTracks().forEach(element => {element.stop(); }); screenCaptureEl.style.visibility = 'hidden'; localMediaStream = null; return false; } //拿到本地媒体流,并显示到video元素中 localMediaStream = await getUserMedia(); videoEl.srcObject = localMediaStream; screenCaptureEl.style.visibility = 'visible'; } // 截屏点击事件 const showImg = document.querySelector('.show-img'); screenCaptureEl.onclick = () =>{ const imgBase64 = screenCapture(videoEl); const img = document.createElement('IMG'); img.src = imgBase64; showImg.appendChild(img) } </script> </body> </html>
效果
硬件支持
没有摄像头的可以考虑 虚拟摄像头wecam
http://www.e2esoft.cn/wecam/
来模拟摄像头输出