wordpress 1.0手機一鍵優(yōu)化
產(chǎn)品提了這樣一個需求:
移動端拍照上傳后圖片不保存在用戶設(shè)備上,試了好幾種方法,uni-file-picker、uni.chooseImage、input type=‘file’,安卓手機都會默認(rèn)把圖片保存在手機,于是各種查資料,找到了以下方法,已驗證可行。
1、獲取攝像頭權(quán)限并顯示視頻流:?
使用navigator.mediaDevices.getUserMedia()獲取攝像頭權(quán)限,?并將視頻流顯示在video標(biāo)簽中。?
2、拍照:?
使用HTML的canvas標(biāo)簽來截取當(dāng)前攝像頭的畫面,?并將其轉(zhuǎn)換為圖片格式。?
3、上傳圖片:?
使用uniapp的uni.uploadFile()方法將圖片上傳到服務(wù)器。?
<view class="container"><button @click="initCamera">打開攝像頭</button><button @click="takePhoto">拍照</button>
</view>
data() {return {stream: null,videoElement: null}}
mounted() {this.createVideoElement()
},methods: {createVideoElement() {// 一定要用createElement創(chuàng)建 video和canvas 元素,否則用不了其中的方法this.videoElement = document.createElement('video')this.videoElement.setAttribute('autoplay', '')this.videoElement.setAttribute('muted', '')this.videoElement.setAttribute('playsinline', '')// 添加到 DOM 中const container = document.querySelector('.container')container.appendChild(this.videoElement)},async initCamera() {if (this.stream) {this.stopCamera()}try {const constraints = { video: { facingMode: 'environment' }}const stream = await navigator.mediaDevices.getUserMedia(constraints)this.stream = streamthis.videoElement.srcObject = stream} catch (error) {console.error('Error accessing camera:', error)}},// 關(guān)閉攝像頭stopCamera() {if (this.stream) {this.stream.getTracks().forEach(track => track.stop())this.stream = nullthis.videoElement.srcObject = null}},takePhoto() {this.captureImage()this.stopCamera()},async captureImage() {const canvas = document.createElement('canvas')canvas.width = this.videoElement.clientWidthcanvas.height = this.videoElement.clientHeightconst ctx = canvas.getContext('2d')ctx.drawImage(this.videoElement, 0, 0, canvas.width, canvas.height)// 轉(zhuǎn)化成base64的編碼格式const dataUrl = canvas.toDataURL('image/jpeg')this._uploadFileBase64(dataUrl)},// 上傳到遠(yuǎn)程地址_uploadFileBase64(imgUrl) {uploadFileBase64(imgUrl).then(response => {if (response && response.SavePath) {console.log(response.SavePath)this.$uniToast('上傳成功')} else {this.$uniToast('上傳失敗')}})}
}