Painter通过 json 数据形式,来进行动态渲染并绘制出图片。
Painter 的优势
文件源码和文档地址:https://gitee.com/jackhunx/Painter
下载文件保存到components文件夹下
//在需要使用的页面json中引入
"usingComponents": {
"painter":"/components/painter/painter"
}
wxml
<!-- 海报弹框 -->
<van-popup show="{{isPosterShow}}" bind:close="closePosterFn" custom-style="background: none;">
<view class="poster">
<image bind:tap="saveImageFn" src="{{posterImageUrl}}" mode=""/>
<text>点击图片,保存至手机相册</text>
</view>
</van-popup>
<painter palette="{{posterData}}" bind:imgOK="onImageOK" />
js
var app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
isPosterShow: false,//海报弹框
qrCodeUrl: "",//二维码图片路径
posterData: {},//海报数据
posterImageUrl: "",//海报图片
},
//绘制海报
drawPosterFn(){
wx.showLoading({
title: '生成中',
})
this.setData({
posterData: {
background: '背景颜色或背景图片地址',
width: '1164rpx',
height: '1548rpx',
views: [
{
type: "text",
text: "文字内容",
css: {
top: "256rpx",
left: "82rpx",
width: "1000rpx",
fontSize: "72rpx",
color: "#0159BB",
maxLines: 2,
lineHeight: "108rpx",
textAlign: "center",
fontWeight: "bold"
}
},
{
type: 'image',
url: "二维码图片地址",
css: {
top: '680rpx',
left: '264rpx',
width: '640rpx',
height: '640rpx',
},
}
],
}
})
},
//监听海报是否生成成功
onImageOK(e){
wx.hideLoading();
this.setData({
isPosterShow: true,
posterImageUrl: e.detail.path
})
},
//保存图片到本地
saveImageFn(){
let that = this
wx.saveImageToPhotosAlbum({
filePath: this.data.posterImageUrl,
success(res) {
wx.hideLoading()
wx.showToast({
title: '保存成功',
icon: "success",
duration: 1000
})
},
fail(err) {
console.log(err)
if(err.errMsg == "saveImageToPhotosAlbum:fail auth deny"){
wx.showModal({
content: '检测到您没有授权保存到相册权限,是否去设置打开?',
confirmText: "确认",
cancelText: "取消",
success: function(res) {
//点击“确认”时打开设置页面
if (res.confirm) {
wx.openSetting({
success () {
that.savePhoto();
}
})
} else {
}
}
});
}else if(err.errMsg == "saveImageToPhotosAlbum:fail privacy permission is not authorized"){
app.showMsg("没有同意用户隐私协议!");
}else if(err.errMsg == "saveImageToPhotosAlbum:fail privacy permission is not authorized in gap"){
app.showMsg("保存失败!");
}else{
app.showMsg(err.errMsg);
}
}
})
},
//下载图片地址并保存到相册,提示保存成功
savePhoto() {
wx.saveImageToPhotosAlbum({
filePath: this.data.posterImageUrl,
success(res) {
wx.hideLoading()
wx.showToast({
title: '保存成功',
icon: "success",
duration: 1000
})
},
fail() {
wx.showToast({
title: '保存失败',
icon: "error",
duration: 1000
})
}
})
},
//关闭海报弹框
closePosterFn(){
this.setData({
isPosterShow: false
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
this.drawPosterFn()
},
})