返回
uni-app自定义摄像头拍照添加人物框
前端
2024-01-16 14:09:43
uni-app 是一款非常流行的跨平台开发框架,它可以帮助我们轻松构建移动端应用。uni-app 中提供了很多组件,其中就包括 camera 组件,我们可以使用它来实现自定义相机功能。
一、效果
效果中包含相册选择,拍照,切换摄像头。
二、知识预备
需要用到 uni 的以下几个组件:
- camera 组件:https://uniapp.dcloud.io/component/camera
- image 组件:https://uniapp.dcloud.io/component/image
- view 组件:https://uniapp.dcloud.io/component/view
- button 组件:https://uniapp.dcloud.io/component/button
三、实现过程
1. 在页面中引入 camera 组件
<template>
<view>
<camera id="camera" @error="error" @frame-sent="frameSent"></camera>
</view>
</template>
2. 在 script 标签中定义 camera 组件的属性和方法
export default {
data() {
return {
cameraId: 'camera' // 相机组件的 id
}
},
methods: {
error(err) {
console.log(err)
},
frameSent(res) {
// 拍照成功后,将图片保存到本地相册
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath
})
}
}
}
3. 在 style 标签中定义 camera 组件的样式
#camera {
width: 100%;
height: 100%;
}
4. 在页面中引入 image 组件和 view 组件
<template>
<view>
<camera id="camera" @error="error" @frame-sent="frameSent"></camera>
<image id="image" src="{{ imageUrl }}"></image>
</view>
</template>
5. 在 script 标签中定义 image 组件和 view 组件的属性和方法
export default {
data() {
return {
cameraId: 'camera', // 相机组件的 id
imageUrl: '' // 图片的路径
}
},
methods: {
error(err) {
console.log(err)
},
frameSent(res) {
// 拍照成功后,将图片路径赋值给 imageUrl
this.imageUrl = res.tempFilePath
}
}
}
6. 在 style 标签中定义 image 组件和 view 组件的样式
#image {
width: 100%;
height: 100%;
}
.view {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
opacity: 0.5;
}
7. 在页面中引入 button 组件
<template>
<view>
<camera id="camera" @error="error" @frame-sent="frameSent"></camera>
<image id="image" src="{{ imageUrl }}"></image>
<view class="view"></view>
<button @click="takePhoto">拍照</button>
</view>
</template>
8. 在 script 标签中定义 button 组件的属性和方法
export default {
data() {
return {
cameraId: 'camera', // 相机组件的 id
imageUrl: '' // 图片的路径
}
},
methods: {
error(err) {
console.log(err)
},
frameSent(res) {
// 拍照成功后,将图片路径赋值给 imageUrl
this.imageUrl = res.tempFilePath
},
takePhoto() {
// 拍照
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['camera']
}).then(res => {
// 成功后将图片路径赋值给 imageUrl
this.imageUrl = res.tempFilePaths[0]
}).catch(err => {
console.log(err)
})
}
}
}
9. 在 style 标签中定义 button 组件的样式
.button {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #fff;
color: #000;
font-size: 16px;
}
四、效果演示
运行项目,点击“拍照”按钮,即可拍照并保存到本地相册。