调用浏览器的拍照api拍照!

要拍照,请调用navigator的getUserMedia,它接收3个参数 ,第一个配置,第二个成功回调,第三个失败的回调

<video width="400" height="300"></video>
<button>hello</button>
<canvas width="400" height="300"></canvas>
<a>
  <button id="download">download</button>
</a>    

js:

const $ = document.querySelector.bind(document)
const video = $('video')
const btn = $('button')
const canvas = $('canvas')
const ctx = canvas.getContext('2d')
const img = $('img')
const dl = $('#download')
const a = $('a')

navigator.getUserMedia({
  video: true, //是否使用摄像头
  audio: false, //是否使用音频
}, stream => {
  video.srcObject = stream
  video.play()
}, err=> {
  console.error('[err ]: ' + err)
})
btn.onclick = () => {
  ctx.drawImage(video, 0, 0, 400, 300)
  dl.style.setProperty('display', 'inline-block')
  const base64 = canvas.toDataURL()
  a.download = 'i.png'
  a.href = URL.createObjectURL(base64ToUint8Array(base64.split(',')[1]))
}


function base64ToUint8Array(base64, type) {
  const str = atob(base64)
  const len = str.length
  const u8Arr = new Uint8Array(len)
  for (let i = 0; i < len ; i++ ){
    u8Arr[i] = str.codePointAt(i)
  }
  return new Blob([u8Arr], {type})
}

  

 

posted @ 2021-03-11 23:21  nextYearToday  阅读(115)  评论(0)    收藏  举报