手摸手实现js自拍 开启摄像头 获取摄像头视频流
<!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> </head> <body> <div> <video id="video" autoplay style="">#000;"></video> <canvas style="display: none;" id="canvas"></canvas> <img id="img" src="" alt="这是个照片"> </div> <button id="btn_snap" onclick="takePhoto()">拍照</button> <button onclick="save()">保存</button> </body> <script> const cvs = document.getElementById('canvas') const video = document.getElementById('video') // 宽度设置400 cvs.width = cvs.height = video.width = video.height = 400 const { width, height } = cvs const ctx = cvs.getContext('2d') // 定义吊起摄像头要用的参数格式固定 const constraints={ video:{ width, height } } // 媒体设备获取媒体摄像 stream里面的数据流 navigator.mediaDevices.getUserMedia(constraints).then(stream=>{ video.srcObject=stream // 等数据流加载好之后就会触发这个事件 一旦触发就使用play方法捕捉到画面 video.onloadedmetadata=()=> video.play() }) // 实现拍照 function takePhoto(){ // canvas可以直接化video ctx.drawImage(video,0,0,width,height) // 直接把图片打出来 document.getElementById('img').src=canvas.toDataURL('image/png') console.log( ctx.drawImage(video,0,0,width,height)); console.log(canvas.toDataURL('image/png')); } // 保存-将画布内容保存为图片 const save = () => { // 将canvas上的内容转成blob流 cvs.toBlob(blob => { const date = Date.now().toString() const a = document.createElement('a') a.download = `${date}.png` a.href = URL.createObjectURL(blob) a.click() a.remove() }) } </script> </html>
本文来自博客园,作者:樱桃树下的约定,转载请注明原文链接:https://www.cnblogs.com/tcyweb/p/17603123.html