<div id="box">
    <p>
      <button onclick="openMedia()">打开</button>
      <button onclick="closeMedia()">关闭</button>
      <button onclick="drawMedia()">截取</button>
    </p>
    <video id="video"></video>
    <img id="faceImg" src="" />
  </div>
    var mediaStreamTrack;

    //启动摄像头
    function openMedia () {
      //请求媒体类型参数
      const constraints = { audio: false, video: { width: 260, height: 260 } }
      navigator.mediaDevices.getUserMedia(constraints)
        .then(
          (mediaStream) => {
            const video = document.querySelector('video')
            mediaStreamTrack = mediaStream
            video.srcObject = mediaStream;
            video.onloadedmetadata = (e) => { video.play() };
          }
        ).catch((err) => { console.log(err.name + ": " + err.message) });
    }

    //关闭摄像头
    function closeMedia () {
      mediaStreamTrack.getVideoTracks().forEach(track => {
        track.stop();
      })
    }

    //截取图片
    function drawMedia () {
      const video = document.getElementById('video')
      const faceImg = document.getElementById('faceImg')
      const canvas = document.createElement("canvas")
      canvas.width = video.clientWidth
      canvas.height = video.clientHeight
      canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height)
      const faceURL = canvas.toDataURL("image/png")  //将图片转成base64格式
      faceImg.src = faceURL
    }
Last Updated:
Contributors: pengrengui