介绍
HTML5 的 getUserMedia API 为用户提供访问硬件设备媒体(摄像头、视频、音频、地理位置等)的接口,基于该接口,开发者可以在不依赖任何浏览器插件的条件下访问硬件媒体设备。文章来源:https://www.toymoban.com/news/detail-617457.html
另外,主流浏览器 Firefox、Chrome、Safari、Opera 等等已经全面支持。文章来源地址https://www.toymoban.com/news/detail-617457.html
一、获取视频流,并用 video 标签播放
<video id="video" autoplay></video>
const videoConstraints = { width: 1366, height: 768 };
const videoNode = document.querySelector('#video');
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });
videoNode.srcObject = stream;
videoNode.play();
二、多个摄像头设备切换
// enumerateDevices获取所有媒体设备
const mediaDevices = await navigator.mediaDevices.enumerateDevices();
// 通过设备实例king属性videoinput,过滤获取摄像头设备
const videoDevices = mediaDevices.filter(item => item.kind === 'videoinput') || [];
// 获取前置摄像头
const videoDeviceId = videoDevices[0].deviceId;
const videoConstraints = { deviceId: { exact: videoDeviceId }, width: 1366, height: 768 };
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });
// 获取后置摄像头
const videoDeviceId = videoDevices[1].deviceId;
const videoConstraints = { deviceId: { exact: videoDeviceId }, width: 1366, height: 768 };
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });
// 依次类推...
三、拍照保存图片
// 通过canvas捕捉video流,生成base64格式图片
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = 1366;
canvas.height = 768;
context.drawImage(videoNode, 0, 0, canvas.width, canvas.height);
download(canvas.toDataURL('image/jpeg'));
// 下载图片
function download (src) {
if (!src) return;
const a = document.createElement('a');
a.setAttribute('download', new Date());
a.href = src;
a.click();
}
关闭摄像头设备
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });
// 3s后关闭摄像头
setTimeout(function () {
stream.getTracks().forEach(track => track.stop());
stream = null;
}, 3000);
到了这里,关于javascript - 实现拍照功能(详细示例代码)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!