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

2022-10-20,,,,

开篇

最近在做一个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();
    }

4、关闭摄像头设备

let stream = await navigator.mediadevices.getusermedia({ audio: true, video: videoconstraints });
    // 3s后关闭摄像头
    settimeout(function () {
        stream.gettracks().foreach(track => track.stop());
        stream = null;
    }, 3000);

到此完成简单的相机拍照功能

摄像

摄像基本流程,是录制一段视频流并保存为音视频文件。html5 mediarecorder对象提供了多媒体录音和录视频功能。

浏览器兼容性如下:

从上图所示,浏览器对mediarecorder兼容性远不如getusermedia,目前只有chrome、firefox对mediarecorder支持较好。

==注意:摄像预览播放器video标签要设置静音muted(消除回声导致的刺耳噪音)==

const videoconstraints = { width: 1366, height: 768 };
    let stream = await navigator.mediadevices.getusermedia({ audio: true, video: videoconstraints });
    let mediarecorder = new mediarecorder(stream);
    let mediarecorderchunks = []; // 记录数据流
   
    mediarecorder.ondataavailable = (e) => {
        mediarecorderchunks.push(e.data);
    };
    
    mediarecorder.onstop = (e) => {
        // 通过blob对象,创建文件二进制数据实例。
        let recorderfile = new blob(mediarecorderchunks, { 'type' : mediarecorder.mimetype });
        mediarecorderchunks = [];
        const file = new file([this.recorderfile], (new date).toisostring().replace(/:|\./g, '-') + '.mp4', {
            type: 'video/mp4'
        });
        download(url.createobjecturl(file));
        // 下载视频
        function download (src) {
            if (!src) return;
            const a = document.createelement('a');
            a.setattribute('download', new date());
            a.href = src;
            a.click();
        }
    };
    
    mediarecorder.stop(); // 停止录制,触发onstop事件

总结

通过以上实战,相信读者已经掌握基础相机功能,拍照、摄像、保存文件等。由于应用项目非个人项目,源码不公开,有兴趣的朋友,不妨动手一试。

《HTML5拍照和摄像机功能实战详解.doc》

下载本文的Word格式文档,以方便收藏与打印。