<template>
<view>
<view style="display: flex;justify-content: center;flex-wrap: wrap;">
<canvas canvas-id="shareCanvas" style="width:354px;height: 461px;"></canvas>
<button v-if="shareImage" @click="downLoad">下载</button>
</view>
</view>
</template>
<script>
import {
qrCode,
dlBackground
} from "../../services/api.js"
export default {
data() {
return {
codeObj: {},
imgUrl: "",
image: getApp().globalData.image,
backgorondImg: "",
shareImage: "",
}
},
onLoad() {
this.dlBackgrounds();
this.getQrCode();
},
methods: {
dlBackgrounds() {
dlBackground().then(res => {
this.backgorondImg = this.image + res.result;
})
},
getQrCode() {
let that = this;
qrCode({
id: uni.getStorageSync('USER_INFO')
}).then(res => {
uni.showLoading({
title:"资源加载中"
})
if (res.code == 200) {
that.codeObj = JSON.parse(res.result);
// 公众号生成二维码
uni.request({
url: `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${ decodeURIComponent(that.codeObj.ticket)}`,
method: 'GET',
header: {
'Content-Type': 'application/json',
},
responseType: "arraybuffer",
success: res => {
if (res.data) {
// 拼接base64图片 请求一定要加 responseType: "arraybuffer"
that.imgUrl = 'data:image/jpg;base64,' + uni.arrayBufferToBase64(res.data);
// 不能使用请求图片下载至本地
uni.downloadFile({
url: that.backgorondImg, //仅为示例,并非真实的资源
success: (res) => {
if (res.statusCode == 200) {
that.shareImage = res.tempFilePath;
var code = that.imgUrl;
/*code是指图片base64格式数据*/
//声明文件系统
const fs = wx.getFileSystemManager();
//随机定义路径名称
var times = new Date().getTime();
var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
//将base64图片写入
fs.writeFile({
filePath: codeimg,
data: code.slice(22),
encoding: 'base64',
success: (res) => {
// 生成画布
const ctx = wx.createCanvasContext('shareCanvas');
ctx.drawImage(this.shareImage, 0, 0, 354, 461)
ctx.drawImage(codeimg, 116, 318, 120, 120)
ctx.draw();
uni.hideLoading()
}
});
}
}
});
}
},
})
}
});
},
// 下载图片到本地
downLoad() {
uni.showToast({
title: "下载中",
duration: 3000,
icon:"loading"
})
uni.canvasToTempFilePath({
canvasId: 'shareCanvas',
quality: 1,
complete: (res) => {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(e) {
uni.showToast({
title: '保存成功',
icon: "none"
});
},
fail(e) {
uni.showToast({
title: '下载失败,错误原因:' + e.errMsg,
icon: "none"
});
}
});
}
});
},
}
}
</script>
<style lang="scss">
.img {
width: 300rpx;
height: 300rpx;
}
button {
width: 80%;
margin: 100rpx 0rpx;
}
</style>
小程序canvas画布宣传页,base64图片放在画布上,真机不展示的bug
于 2023-04-28 16:57:23 首次发布