100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 微信小程序调用摄像头实现拍照

微信小程序调用摄像头实现拍照

时间:2022-07-03 17:16:00

相关推荐

微信小程序调用摄像头实现拍照

微信小程序开发文档:https://developers./miniprogram/dev/component/camera.html

首先,需要用户授权摄像头权限,这一步是必须的

具体步骤:

获取用户当前授权状态,看是否已经授权,如果已经授权直接显示摄像头如果用户还没有授权,则调起授权弹框,用户允许授权则显示摄像头如果用户不允许,则提示用户去设置页面打开摄像头权限

用户授权之后,就可以进行拍摄了,微信的camera组件无法显示为圆形,我这里是用一张图片遮盖了

上代码:

wxml:

<view class='camera'><image src="/images/border.png" mode="widthFix"></image><camera wx:if="{{isAuth}}" device-position="back" flash="off" binderror="error"></camera></view><button class="takePhoto" type="primary" bindtap="takePhoto">拍照</button>

wxss:

.camera {width: 430rpx;height: 430rpx;border-radius: 50%;margin: 20px auto 0;position: relative;}.camera image {position: absolute;width: 100%;height: 100%;z-index: 10;}.camera camera {width: 428rpx;height: 428rpx;}button.takePhoto:not([size='mini']) {position: fixed;bottom: 0;left: 0;width: 100vw;height: 90rpx;border-radius: 0;}

js:

Page({data: {isAuth: false,src: ''},onLoad() {const _this = thiswx.getSetting({success: res => {if (res.authSetting['scope.camera']) {// 用户已经授权_this.setData({isAuth: true})} else {// 用户还没有授权,向用户发起授权请求wx.authorize({scope: 'scope.camera',success() { // 用户同意授权_this.setData({isAuth: true})},fail() { // 用户不同意授权_this.openSetting().then(res => {_this.setData({isAuth: true})})}})}},fail: res => {console.log('获取用户授权信息失败')}})},// 打开授权设置界面openSetting() {const _this = thislet promise = new Promise((resolve, reject) => {wx.showModal({title: '授权',content: '请先授权获取摄像头权限',success(res) {if (res.confirm) {wx.openSetting({success(res) {if (res.authSetting['scope.camera']) { // 用户打开了授权开关resolve(true)} else { // 用户没有打开授权开关, 继续打开设置页面_this.openSetting().then(res => {resolve(true)})}},fail(res) {console.log(res)}})} else if (res.cancel) {_this.openSetting().then(res => {resolve(true)})}}})})return promise;},takePhoto() {const ctx = wx.createCameraContext()ctx.takePhoto({quality: 'high',success: (res) => {this.setData({src: res.tempImagePath})wx.previewImage({current: res.tempImagePath, // 当前显示图片的http链接urls: [res.tempImagePath] // 需要预览的图片http链接列表})}})}})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。