微信小程序二维码生成海报
使用canvas画布进行画图
效果图
>
<view class="container">
<image
class="instead"
show-menu-by-longpress // 这个用于设置 长按识别小程序码
mode="widthFix"
src="{{img}}"
/>
<canvas
id="myCanvas"
canvas-id="myCanvas"
style="width:{{width}}px; height:{{height}}px;"
></canvas>
</view>
data(){
width:0,
height:0,
ratio:0,
},
.container{
height:100vh;
width:100%;
display:flex;
justify-content: center;
align-items: center;
}
.container .instead{
width:600rpx;
}
.container .canvas-in{
border:1px solid #000;
zoom:40%;
position: fixed;
top: -1000000000px; // 可以将canvas隐藏
}
const app = getApp();
onLoad:function(){
this.setScreenRatio()
},
// 初始化数据
setScreenRatio(){
const ORI = 375; // 设计稿里的高度 如果设计稿有背景的话就使用背景图的高度
wx.getSystemInfo({ // 获取手机型号的信息
success:res=>{ // 设置画布的大小 我希望整个画布就是我的背景图
this,setData({
retio: ORI / res.windowWidth || 1,
width:res.screenWidth * 2,
height:1160 / (ORI_WIDTH / res.windowWidth || 1) //这里是背景图的大小
})
},
fail:err=>{
conosle.log(err)
}
})
},
// 设置画布
drawPoster(code,avatar){
let that = this;
let bgUrl = "/assets/image/bg.png";
let ctx = wx.createCanvasContext('myCanvas'); // 获取画布信息
let bgWidth = 750 / this.data.ratio; // 设置背景图片大小
let bgHeight = 1160 / this.data.ratio;
let Text = "点击保存图中小程序码";
ctx.drawImage(url,0,0,bgWidth,bgHeight);
ctx.setFillStyle('#000');
// (bgWidth - ctx.measureText(Text).width)*0.5 这里可以实现文字在图中水平居中对齐
ctx.fillText(Text,(bgWidth - ctx.measureText(Text).width)*0.5,fontY);
ctx.draw(true,()=>{
// 在渲染完后直接将图片保存下来
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success:res=>{
console.log(res)
// 生成图片完成
wx.hideLoading({
success: (res) => {},
})
that.setData({
img:res.tempFilePath
})
},
fail:err=>{
console.log(err)
}
})
})
}
canvas当中不能使用网络图片,所以我们需要将图片缓存到本地当中
_GETQRCODE(token){
let avatar = app.globalData.userInfo.avatarUrl;
let code = '';
// 等待渲染完成
wx.showLoading({
title: '加载中',
})
QRCODE(token).then(res=>{
this.downLoad(res.data).then(res=>{
code = res.path
this.downLoad(avatar).then(res=>{
this.drawPoster(code,res.path)
})
})
}).catch(err => {
console.log(err)
})
}
downLoad(url){
return new Promise((resolve,reject) => {
wx.getImageInfo({
src: url,
success:res=>{
resolve(res)
},
fail:err=>{
reject(err)
}
})
})
},
在获取图片的时候,要注意域名是否有设置,有无加HTTPS证书
如果没有的话,可以在开发者工具里设置(勾上)
点击保存
saveQRcode(){
let img = this.data.img
wx.saveImageToPhotosAlbum({
filePath: img,
success:res=>{
console.log("放入相册成功")
wx.showToast({
title: '保存成功',
})
},
fail:err=>{
wx.showToast({
title: '保存失败',
icon: "none"
})
}
})
}
需要用户授权才能保存相册
主要在于图片的加载和渲染