前端调用电脑摄像头

项目中需要前端调用,所以做了如下操作
先看一下效果吧
主要是基于vue3,通过canvas把画面转成base64的形式,然后是把base64转成
file文件,最后调用了一下上传接口


以下是代码

进入页面先调用一下摄像头

javascript 复制代码
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then((stream) => {
      video.value.srcObject = stream
    })
    .catch((error) => {
      console.error(error)
    })
  state.photoUrl = ''
  state.photo = true

拍照

javascript 复制代码
const canvas = document.createElement('canvas')
  canvas.width = video.value.videoWidth
  canvas.height = video.value.videoHeight
  canvas.getContext('2d').drawImage(video.value, 0, 0, canvas.width, canvas.height)
  state.photoUrl = canvas.toDataURL('image/png')

转base64

javascript 复制代码
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  })

完整代码

javascript 复制代码
<template>
  <div>
    <div>
      <div>摄像头实时画面</div>
      <div class="hm">
        <video ref="video" v-if="state.photo" autoplay></video>
        <img :src="state.photoUrl" v-else>
      </div>
    </div>
    <div class="maT10">
      <el-button @click="takePhoto">
        拍照
      </el-button>
      <el-button @click="retake">
        重拍
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="photo">
import axios from 'axios'
const state = reactive({
  photo: true,
  photoUrl: '',
})
const video = ref()

const takePhoto = () => {
  const canvas = document.createElement('canvas')
  canvas.width = video.value.videoWidth
  canvas.height = video.value.videoHeight
  canvas.getContext('2d').drawImage(video.value, 0, 0, canvas.width, canvas.height)
  state.photoUrl = canvas.toDataURL('image/png')

  clearVideo()
  state.photo = false
  let file = base64ImgtoFile(state.photoUrl)
  let param = new FormData()
  param.append('file', file, file.name)
  param.append('fileReName', 'true')
  let config = {
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: 'token',  //此处是token
    },
  }

  let url = import.meta.env.VITE_API_URL + '/api/admin/file/upload-file'
  axios.post(url, param, config).then((response) => {})
}
const base64ImgtoFile = (dataurl, filename = 'file') => {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  })
}
const clearVideo = () => {
  const stream = video.value.srcObject
  const tracks = stream.getTracks()
  tracks.forEach((track) => {
    track.stop()
  })
  video.value.srcObject = null
}

const retake = () => {
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then((stream) => {
      video.value.srcObject = stream
    })
    .catch((error) => {
      console.error(error)
    })
  state.photoUrl = ''
  state.photo = true
}

onMounted(() => {
  retake()
})
//在离开当前页面的时候把摄像头关了,不然页面一直会显示摄像头的图标
onBeforeUnmount(() => {
  video.value.srcObject = null
})
</script>

<style scoped lang="scss">
.hm {
  width: 400px;
  height: 300px;
  video,
  img {
    width: 100%;
  }
}
</style>
相关推荐
雨雨雨雨雨别下啦16 分钟前
【从0开始学前端】vue3简介、核心代码、生命周期
前端·vue.js·vue
simon_934934 分钟前
受够了压缩和收费?我作为一个码农,手撸了一款无限容量、原图直出的瀑布流相册!
前端
e***87701 小时前
windows配置永久路由
android·前端·后端
Dorcas_FE2 小时前
【tips】动态el-form-item中校验的注意点
前端·javascript·vue.js
小小前端要继续努力2 小时前
前端新人怎么更快的融入工作
前端
四岁爱上了她2 小时前
input输入框焦点的获取和隐藏div,一个自定义的下拉选择
前端·javascript·vue.js
fouryears_234172 小时前
现代 Android 后台应用读取剪贴板最佳实践
android·前端·flutter·dart
boolean的主人2 小时前
mac电脑安装nvm
前端
用户1972959188912 小时前
WKWebView的重定向(objective_c)
前端·ios
烟袅3 小时前
5 分钟把 Coze 智能体嵌入网页:原生 JS + Vite 极简方案
前端·javascript·llm