HTML5拍照和摄像机功能实战详解

2020-04-25 08:05:32易采站长站整理

开篇

最近在做一个chrome app的云相机应用,应用包括拍照、摄像、保存照片视频、上传文件等等核心功能,其中涉及到很多HTML5对媒体流相关的API。写这篇文章的目的,其一是总结梳理知识点,最重要是希望对有相关需求的读者提供一些指导。

注:本篇文章以实战为准,理论知识不做过多介绍。

拍照

HTML5的getUserMedia API为用户提供访问硬件设备媒体(摄像头、视频、音频、地理位置等)的接口,基于该接口,开发者可以在不依赖任何浏览器插件的条件下访问硬件媒体设备。

浏览器兼容性如下:

从上图可以看到,主流浏览器Firefox、Chrome、Safari、Opera等等已经全面支持。

1、获取视频流,并用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();

2、多个摄像头设备,如何切换?


// 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 });

// 依次类推...

3、拍照保存图片


// 通过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();