获取摄像头权限,并且在video元素上呈现出来

判断摄像头兼容问题

<video id="video"></video>

// 定义方法访问用户媒体设备的兼容方法

    function getUserMedia(constraints, success, error) {

      if (navigator.mediaDevices.getUserMedia) {

        console.log("最新的标准API");

        navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);

      } else if (navigator.webkitGetUserMedia) {

        console.log("webkit核心浏览器");

        navigator.webkitGetUserMedia(constraints, success, error)

      } else if (navigator.mozGetUserMedia) {

        console.log("firfox浏览器");

        navigator.mozGetUserMedia(constraints, success, error);

      } else if (navigator.getUserMedia) {

        console.log("旧版API");

        navigator.getUserMedia(constraints, success, error);

      }

    }

获取videoDOM元素,并且让video承接画面(注意:每次调用都需要重新获取权限)

// 获取元素节点

let video = document.getElementById("video");

let mode = "user"  // 设置使用environment后置摄像头,user为前置摄像头

// 封装开启摄像头方法

function getCamera() {

// 判断用户的兼容,并作出对应的处理

      if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {

        //调用用户媒体设备, 访问摄像头

        getUserMedia({

        // 获取摄像头

          video: {

            width: 400,  // 默认单位px

            height: 300,

            facingMode:  mode, 

          },

        // 获取麦克风

          audio: true

        }, success, error);       

      } else {

        console.log("不支持访问用户媒体");

      }

    }

    // 调用成功的回调

    function success(stream) {     

      //兼容webkit核心浏览器

      let CompatibleURL = window.URL || window.webkitURL;

      //将视频流设置为video元素的源

      mediaStreamTrack = stream.getTracks()[0];     

      video.srcObject = stream;

      video.play();

    }

    // 调用失败的回调

    function error(error) {

      console.log("error", error);

      console.log("访问用户媒体设备失败,请尝试更换浏览器");

    }

切换前后摄像头

function changeMode() {

      mode = mode == "user" ? "environment" : "user";

      mediaStreamTrack.stop();

      getCamera();

}

对当前video元素截图(拍照功能)需要配合canvas标签使用

<button id="getPhoto">拍照</button>

<canvas id="canvas" width="400" height="300"></canvas>

let canvas = document.getElementById('canvas');

let context = canvas.getContext('2d');

// 对按钮添加点击事件(通过DOM0级绑定方便之后事件的解绑-对事件置空即可)

document.getElementById('capture').onclick = function () {

      context.drawImage(video, 0, 0, 400, 300);

    }

点击下载照片

<button id="download">下载</button>

    document.getElementById('download').onclick = () => {

      let photoElement = document.createElement('a');

      photoElement.href = canvas.toDataURL('image/png');

      photoElement.download = '照片名称';

      document.body.append(photoElement);

      photoElement.click();

      document.body.removeChild(photoElement)

    };