uniapp开发微信小程序 -- 调用摄像头
·
参考文章:https://blog.csdn.net/m0_52704391/article/details/144174394
一、调用摄像头扫描二维码:
uni.scanCode({
success: function (res) {
// 拿到的二维码数据
console.log(res.result)
},
fail: function (err) {
that.G.toast(`'扫码失败:${err.errMsg}`)
}
});
二、给图片添加地点和时间水印:
1、配置:
① 在manifest.json中微信小程序勾选配置:

勾选完在源码中查看是否有
"requiredPrivateInfos": ["getLocation"],没有的话,手动添加上
② 在manifest.json源码中声明:

"requiredPrivateInfos": ["getLocation"],
"permission": {
"scope.userLocation": {
"desc": "位置信息效果展示"
}
}
2、在template中新增canvas元素,用于绘制图片:
<!-- 通过样式将canvas在页面中隐藏 -->
<canvas canvas-id="imgCanvas" id="imgCanvas" style="position:fixed;left: 100%;z-index: -1;"></canvas>
<!-- 图片是用来调试看效果的 -->
<image :src="imageSrc" mode="aspectFit" style="width: 600rpx;"></image>
3、在script中引入插件并且在data中新增变量:
//引入腾讯地图插件
import QQMapWX from "@/common/qqmap-wx-jssdk.js"
// 引入新变量
getPositioning: false, // 是否获取了位置信息
location: {}, // 存储时间、地点的信息
imageSrc: '', // 预览图片链接
4、获取地点:
① 判断是否开启定位授权:uni.getSetting
② 判断是否开启定位:uni.authorize
③ 获取定位经纬度:uni.getLocation
④ 根据经纬度逆向解析具体的地址:
(1)使用腾讯地图的文档:https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview
(2)配置额度:

(3)下载sdk,并且解压放在文件夹中:

(4)修改qqmap-wx-jssdk文件中的代码:
错误配置:module.exports = QQMapWX;
正确配置:export default QQMapWX;
⑤ 拿到地址和时间后调用摄像头拍照:uni.chooseMedia
官方文档:https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia
⑥ 拍完照之后添加水印:canvas
⑦ 完整的代码:
getCurrentLocation(){ // 获取当前设备定位
let that = this;
let qqmapsdk = new QQMapWX({
key: '' // 腾讯地图的key
});
that.getPositioning = true // 正在获取定位
let location = {
lng: 0,
lat: 0,
address: "", // 地址
nowTime: '', // 时间
};
uni.getSetting({
success(res) {
//#ifdef MP-WEIXIN
if (res.authSetting['scope.userLocation']) { // 已经开启了定位权限
uni.authorize({
scope: 'scope.userLocation',
success(res) { // 开启了定位
// uni.showLoading({
// title: '正在加载中...',
// mask: true
// });
uni.getLocation({ // 获取经纬度
type: 'gcj02',
success:function (res) {
// 逆向获取城市地址
qqmapsdk.reverseGeocoder({
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: (response) => {
let info = response.result;
location.address = info.formatted_addresses.standard_address + info.formatted_addresses.recommend;
location.nowTime= that.getCurrentTime()
that.location = location
that.getPositioning = false // 获取定位完毕
that.getPhoto()
},
fail: error => {
uni.showToast({
title: '解析具体的位置失败',
icon: 'none',
})
}
});
},
fail: error => {
uni.showToast({
title: '无法获取位置信息!无法使用位置功能',
icon: 'none',
})
}
})
},
fail() {
uni.showModal({
title: '提示',
content: '定位失败,你未开启定位权限,点击开启定位权限',
success: function (res) {
if (res.confirm) {
uni.openSetting({ // 打开定位
success: function (res) {
if (res.authSetting['scope.userLocation']) {
// uni.showLoading({
// title: '正在加载中...',
// mask: true
// });
uni.getLocation({ // 获取经纬度
type: 'gcj02',
success:function (res) {
// 逆向获取城市地址
qqmapsdk.reverseGeocoder({
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: (response) => {
let info = response.result;
location.address = info.formatted_addresses.standard_address + info.formatted_addresses.recommend;
location.nowTime= that.getCurrentTime()
that.location = location
that.getPositioning = false // 获取定位完毕
that.getPhoto()
},
fail: error => {
uni.showToast({
title: '解析具体的位置失败',
icon: 'none',
})
}
});
},
fail: error => {
uni.showToast({
title: '无法获取位置信息!无法使用位置功能',
icon: 'none',
})
}
})
} else {
uni.showToast({
title: '用户未同意地理位置权限,无法使用位置功能',
icon: 'none',
})
}
}
})
}
}
})
}
})
} else {
uni.showModal({
title: '提示',
content: '定位失败,你未开启定位权限,点击开启定位权限',
success: function (res) {
if (res.confirm) {
uni.openSetting({ // 开启定位权限
success: function (res) {
if (res.authSetting['scope.userLocation']) {
console.log('同意')
// uni.showLoading({
// title: '正在加载中...',
// mask: true
// });
uni.getLocation({ // 获取经纬度
type: 'gcj02',
success:function (res) {
// 逆向获取城市地址
qqmapsdk.reverseGeocoder({
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: (response) => {
let info = response.result;
location.address = info.formatted_addresses.standard_address + info.formatted_addresses.recommend;
location.nowTime= that.getCurrentTime()
that.location = location
that.getPositioning = false // 获取定位完毕
that.getPhoto()
},
fail: error => {
uni.showToast({
title: '解析具体的位置失败',
icon: 'none',
})
}
});
},
fail: error => {
uni.showToast({
title: '无法获取位置信息!无法使用位置功能',
icon: 'none',
})
}
})
} else {
uni.showToast({
title: '用户未同意地理位置权限,无法使用位置功能',
icon: 'none',
})
}
}
})
}
}
})
}
//#endif
}
})
},
// 获取当前时间
getCurrentTime() {
var currentTime = new Date();
var year = currentTime.getFullYear(); // 获取当前年份
var month = currentTime.getMonth() + 1; // 获取当前月份(注意月份是从0开始计算的,需要加1)
var day = currentTime.getDate(); // 获取当前日期
var hour = currentTime.getHours(); // 获取当前小时
var minute = currentTime.getMinutes(); // 获取当前分钟
var second = currentTime.getSeconds(); // 获取当前秒数
let str = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
return str
},
// 进行拍照
getPhoto() {
let that = this
if (this.getPositioning) {
uni.showToast({
title: '请稍后,定位中',
icon: 'error',
})
return
} else {
uni.chooseMedia({
mediaType: ['image'], //文件类型
sourceType: ['camera'], //来源
success: (res) => {
const tempFilePaths = res.tempFiles[0];
this.operaImg(tempFilePaths) // 加工照片
}
});
}
},
operaImg(obj) {
let that = this;
let path = obj.tempFilePath;
uni.getImageInfo({
src: path,
success: (res) => {
let width = res.width / 10;
let height = res.height / 10;
// 获取当前时间
const {nowTime:roleNameInfo, address: location} = that.location
let ctx = uni.createCanvasContext('imgCanvas', that);
ctx.drawImage(res.path, 0, 0, width, height); //先画出上传的图片
setTimeout(() => { // 制作水印
const backgroundColor = 'rgba(0, 0, 0, 0.5)'; // 半透明黑色
const backgroundHeight = 40;
ctx.setFillStyle(backgroundColor)
//填充一个矩型ctx.fillRect(矩形路径左上角的x坐标,矩形路径左上角的y坐标,矩形路径的宽度,矩形路径的高度)
ctx.fillRect(0, height - backgroundHeight - 40, width, backgroundHeight)
let info = roleNameInfo + location
// 设置文本样式
ctx.setFontSize(10);
ctx.setFillStyle('white')
//文本超出图片宽度后换行
this.drawWrappedText(ctx, info, 0, height - 70, 10, width)
ctx.draw(false, () => [
setTimeout(() => { //使用定时给水印生成时间避免bug
uni.canvasToTempFilePath({ //将处理完成的画布转换成图片
width: width,
height: height,
canvasId: 'imgCanvas',
success: (file) => {
obj.path = file.tempFilePath
that.imageSrc = obj.path
console.log('最终要给后端的路径', obj.path)
},
fail: (e) => {
uni.showToast({
title: "上传失败,请再次尝试!",
icon: 'none',
duration: 2000
});
}
}, that)
}, 200)
])
}, 300);
},
})
},
// 计算文本换行宽高,换行逻辑
drawWrappedText(ctx, text, x, y, lineHeight, maxWidth) {
const words = text.split('');
let line = '';
const lines = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
const testLine = line + word;
const metrics = ctx.measureText(testLine);
if (metrics.width > maxWidth && i > 0) {
lines.push(line);
line = word;
} else {
line = testLine;
}
};
⑧ 效果图:

更多推荐
所有评论(0)