生活随笔
收集整理的這篇文章主要介紹了
Vue 调用PC摄像头拍照
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
項(xiàng)目需求:可以本地上傳頭像,也可以選擇拍攝頭像上傳。
組件:
Camera組件:實(shí)現(xiàn) 打開(kāi)、關(guān)閉攝像頭、繪制、顯示圖片、用于上傳CameraDialog組件:使用ElementUI dialog組件 展示攝像頭UI效果外部調(diào)用CameraDialog組件,實(shí)現(xiàn)拍攝頭像上傳功能本地上傳可使用原生input、也可使用ElementUI upload組件
操作邏輯:
新增時(shí)將頭像圖片轉(zhuǎn)為base64調(diào)用接口提交,返回url地址用于前端展示替換時(shí),先執(zhí)行刪除操作,在依新增操作執(zhí)行。本地上傳原理跟拍攝上傳一致
具體實(shí)現(xiàn)方法:
<template
><div
class="camera-box"><video id
="video" :width
="videoWidth" :height
="videoHeight" v
-show
="!imgSrc"></video
><canvas id
="canvas" :width
="videoWidth" :height
="videoHeight" v
-show
="imgSrc"></canvas
><p
class="camera-p">{{!imgSrc
?'提示:請(qǐng)將頭像居中按"拍照"鍵確認(rèn)':''}}</p
><el
-button type
="primary" @click
="setImage" v
-if="!imgSrc" class="camera-btn">拍照
</el
-button
><el
-button type
="primary" v
-if="imgSrc" @click
="setFileUpload" class="camera-btn">上傳
</el
-button
></div
>
</template
><script
>import {setFileUpload
, deleteFileUpload
, addUserCard
} from "@/api/houseApi";export default {name
: 'Camera',props
: {show
: {type
: Boolean
},deleteData
: {type
: Object
}},data() {return {videoWidth
: '401',videoHeight
: '340',thisCancas
: null,thisContext
: null,thisVideo
: null,imgSrc
: ``,}},mounted() {if (this.show
) this.getCompetence()},methods
: {getCompetence() {var _this
= thisthis.thisCancas
= document
.getElementById('canvas')this.thisContext
= this.thisCancas
.getContext('2d')this.thisVideo
= document
.getElementById('video')if (navigator
.mediaDevices
=== undefined
) {navigator
.mediaDevices
= {}}if (navigator
.mediaDevices
.getUserMedia
=== undefined
) {navigator
.mediaDevices
.getUserMedia = function (constraints
) {var getUserMedia
= navigator
.webkitGetUserMedia
|| navigator
.mozGetUserMedia
|| navigator
.getUserMedia
if (!getUserMedia
) {return Promise
.reject(new Error('getUserMedia is not implemented in this browser'))}return new Promise(function (resolve
, reject
) {getUserMedia
.call(navigator
, constraints
, resolve
, reject
)})}}var constraints
= {audio
: false,video
: {width
: this.videoWidth
, height
: this.videoHeight
, transform
: 'scaleX(-1)'}}navigator
.mediaDevices
.getUserMedia(constraints
).then(function (stream
) {if ('srcObject' in _this
.thisVideo
) {_this
.thisVideo
.srcObject
= stream
} else {