小程序内实现扫码识别跳转功能
在小程序内实现实时扫描并识别二维码的功能
小程序内要实现实时扫码类似微信扫一扫功能,没有废话,只有干货
wxml文件
<view class="backModel" wx:if="{{AwardModelphoto}}">
<view class="back-content1" style="color: #fff;">
<camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 1500rpx;border: 1rpx solid #fff;" mode="scanCode" bindscancode="changeCode" frame-size="medium" resolution="high">
//其中的参数可以参考微信开放文档自行设置(https://developers.weixin.qq.com/miniprogram/dev/component/camera.html)
<view class="blue-line" wx:if="{{showLine}}"></view> //扫码时的一条动态线,可有可无
</camera>
<canvas canvas-id="mycanvas" class="mycanvas" style="width: 750rpx;height: 1500rpx;"> </canvas> //将carmera的图片数据画在canvas上
</view>
</view>
js文件 camera获取图片数据用canvas绘制出图片并上传到本地服务器
var that;
var listener; //声明一个监听参数
page({
data:{
cameraCtx:'',
AwardModelphoto:false
},
onLoad(){
that =this;
},
//扫码识别点击事件
getQrCode(e){
var s= e.detail.result;
var qrcode=s.substring(s.lastIndexOf("/")+1);
this.cameraCtx= wx.createCameraContext();
listener = this.cameraCtx.onCameraFrame((frame) => {
const data = new Uint8ClampedArray(frame.data);
listener.stop() //扫码成功后停止扫码
let destWidth = (frame.width)*0.8 //输出的图片宽度
let destHeight = (frame.height)*0.8 //输出的图片高度
wx.canvasPutImageData({ //把获取到的imageData数据绘制到canvas上
canvasId: 'mycanvas',
x: 0,
y: 0,
width: frame.width,
height: frame.height,
data: data,
success(res) {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: frame.width,
height: frame.height,
destWidth: destWidth,
destHeight: destHeight,
canvasId: 'mycanvas',
fileType:'jpg',
success(res) {
wx.showLoading({
title: '上传中...',
mask:true
})
let tempFilePaths = []
let token = util.getStorageSync(token)
tempFilePaths.push(res.tempFilePath)
wx.uploadFile({
url: url, //上传路径
filePath: tempFilePaths[0],
name: 'files',
formData: {
'token': token
},
success: function (res) {
wx.hideLoading()
if (res.flag) {
wx.showToast({
title: "上传图片失败",
icon: 'none',
duration: 2000
});
return;
}
var imgs = JSON.parse(res.data);
var tempFilePaths = imgs.data.image;
util.setStorageSync("qrcodeImg", tempFilePaths) //将上传后的图片进行保存
that.setData({
src: tempFilePaths,
AwardModelphoto:false
})
},
fail(e){
console.log(e,'上传失败');
listener.stop()
wx.hideLoading()
}
})
},
fail(e){
console.log(e,'自定义扫码失败');
}
})
},
fail(e){
listener.stop()
}
})
})
listener.start()
}
})
wxml如下
.backModel{
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
z-index: 50;
}
.back-content1{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 750rpx;
z-index: 51;
}
.blue-line{
position: absolute;
top: 200rpx;
left: 0;
right: 0;
width: 600rpx;
margin: auto;
border: 2rpx solid #25f848; //线的颜色
box-shadow: 0rpx 0 15rpx #3ef75d;
animation: updown 3s infinite;
z-index: 56;
}
@keyframes updown{
from {top: 200rpx;}
to {top: 1000rpx;}
}
这就是全部的代码了,有需要的可以点赞+收藏