Alibaba Cloud student server as low as 10 yuan a month
demand:
After clicking the invite button, request the interface to get a QR code in base64 format, generate a picture and support long press to save.
tool:
Use applet wx.canvasToTempFilePath, wx.getFileSystemManager, wx.canvasToTempFilePath
html: Need to realize long press to save, so I added a picture and set the transparency to 0. And turn on the long-press save function (small program image attribute)
<div class="inviteshare" >
<canvas canvas-id="shareCanvas" class="inviteshare-canvas" style="width:750rpx;height:1074rpx"></canvas>
<img show-menu-by-longpress v-if="canvasIMG" :src="canvasIMG" class="inviteshare-img"/>
<p class="inviteshare-text">长按可保存图片到系统相册哦~</p>
</div>
css:
page{
background: #FFFAF1;
}
.inviteshare{
&-inviteshare{
display: block;
margin: 0 auto;
}
&-text{
font-size: 28rpx;
font-weight: 400;
color: #FFA970;
text-align: center;
margin-top: 32rpx;
}
&-img{
position: absolute;
top: 0;
left: 0;
right: 0;
margin: 0 auto;
width: 100%;
opacity: 0;
z-index: 1;
height: 1074rpx;
}
}
js: onshow needs to execute drawShareCanvas function
drawShareCanvas: function () {
let self = this;
var rpx = 1
wx.getSystemInfo({
success (res) {
rpx = res.windowWidth / 375
}
})
wx.getImageInfo({
src: self.tempFilePaths,
success (res) {
// 隐藏背景图loading
wx.hideLoading()
const ctx = wx.createCanvasContext('shareCanvas')
// 绘制背景图
ctx.scale(0.5, 0.5)
ctx.drawImage(self.tempFilePaths, 0, 0, 750 * rpx, 1074 * rpx)
// 小程序码
const qrImgSize = 200 * rpx
ctx.drawImage(self.codeImg, 275 * rpx, 609 * rpx, qrImgSize, qrImgSize)
ctx.stroke()
// 绘制其它
ctx.draw()
// 下一步?=> 保存图片到相册
setTimeout(() => {
self.saveAlbum()
}, 200)
tip.toast('长按可保存到系统相册哦~', '', 'none');
},
fail () {
wx.showToast({
title: '生成失败',
icon: 'none'
})
}
})
}
This function will convert from canvas to picture
saveAlbum() {
var that = this
wx.canvasToTempFilePath({
x: 0,
y: 0,
canvasId: 'shareCanvas',
success: function (res) {
that.canvasIMG = res.tempFilePath
},
fail(err) {
console.log(err)
}
}, that)
},
This function converts base64 to network picture
// 将base64图片转网络图片
getBasetoImg(code) {
/* code是指图片base64格式数据 */
// 声明文件系统
return new Promise((resolve, reject) => {
const fs = wx.getFileSystemManager();
const FILE_BASE_NAME = 'tmp_base64src'; // 自定义文件名
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(code) || [];
if (!format) {
return (new Error('ERROR_BASE64SRC_PARSE'));
}
const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
const buffer = wx.base64ToArrayBuffer(bodyData);
fs.writeFile({
filePath,
data: buffer,
encoding: 'binary',
success() {
resolve(filePath);
},
fail() {
reject()
}
});
})
},
If you encounter problems during the development of the applet, please refer to: http://vonasort.com/4j8W