uni-app 小程序 前置攝像頭


在小程序拍照的話,uni.chooseImage()可以直接調取攝像頭拍照,而如果要調用前置攝像頭,這個api就沒有提供了。

在查找官方文檔發現,可以通過camera有提供這么一個組件,頁面內嵌的區域相機組件。

 

頁面代碼
<!-- 相機拍照 -->
<view class="" v-if="ifPhoto">
    <!-- 相機 -->
    <camera :device-position="convert" flash="off" @error="error"class="camera">    </camera>
    <!-- 操作 -->
    <view class="padding bottom_code flex align-center justify-between">
    <!-- 返回 -->
        <view class="code_button" @click="back">
            <image src="../../static/face/icon_return.png" mode="aspectFill"</image>
        </view>
        <!-- 拍照 -->
        <view class="code_button" @click="takePhoto">
            <image src="../../static/face/icon_phone.png" mode="aspectFill"></image>
        </view>
        <!-- 切換攝像頭 -->
        <view class="code_button" @click="showConvert">
            <image src="../../static/face/icon_switch.png" mode="aspectFill"></image>
        </view>
    </view>
</view>
<!-- 照片查看 -->
<view class="" v-else>
    <view class="img_code flex align-center justify-center">
        <image :src="src" mode=""></image>
    </view>
    <!-- 操作 -->
    <view class="padding margin-top flex align-center">
        <button class="cu-btn round bg-green lg" style="width: 350rpx;" @click="anew">重新拍攝</button>
        <button class="cu-btn round bg-yellow lg text-white margin-left" style="width: 350rpx;"@click="uploading">上傳</button>
    </view>
</view>
data內容
    //true 拍照 false 查看
    ifPhoto: true,
    //照片
    src: null,
    //前置或后置攝像頭,值為front, back
    convert: 'front'
JS 放置methods里面
//拍照
takePhoto() {
    const ctx = uni.createCameraContext();
    ctx.takePhoto({
        quality: 'high',
        success: (res) => {
            console.log(res);
            this.src = res.tempImagePath
            if (this.src != null) {
                    this.ifPhoto = false
            }
        }
    });
},
//攝像頭啟動失敗
error(e) {
    console.log(e.detail);
},
//切換攝像頭
showConvert() {
    if (this.convert == 'front') {
        // 后置
        this.convert = 'back'
    } else {
        // 前置
        this.convert = 'front'
    }
},
//返回
back() {
    uni.navigateBack({
        delta: 1
    })
},
//重新
anew() {
    this.ifPhoto = true
},
//上傳
uploading() {
    console.log('上傳');
}
css
<style lang="scss">
// 相機
.camera {
    width: 100%;
    height: 100vh;
}

//操作
.bottom_code {
    position: fixed;
    bottom: 10rpx;
    left: 0;
    width: 100%;
    height: 120rpx;
    // background-color: #1CA6EC;
    
    .code_button {
        width: 90rpx;
        height: 90rpx;

        // border-radius: 50%;
        image {
            width: 100%;
            height: 100%;
        }
    }
}
.img_code {
    width: 100%;
    height: 80vh;
    padding-top: 180rpx;
    
    image {
        width: 100%;
        height: 100%;
    }
}
</style>

最后樣式 因為是模擬器所以沒有 真機調試就可以了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM