官方文档:https://github.com/wechat-miniprogram/wxml-to-canvas
- npm install wxml-to-canvas (下载完后重新构建npm)
- 新建组件-share.js
因为我们涉及到动态参数,所以使用了传参
const wxml = (img, name, organiseid, codeImg)=>{
return `
<view class="container">
<view class="box1">
<image class="img" src='`+img+`'></image>
</view>
<view class="namebox">
<text class="nametext">`+name+`</text>
</view>
<view class="organizebox">
<text class="organizetext">发起方:`+organiseid+`</text>
</view>
<view class="code">
<image class="codeimg" src='`+codeImg+`'></image>
</view>
<view class="activity">
<text class="activitytext">扫码参加活动</text>
</view>
<view class="textboxtwo">
<text class="text">长按识别二维码</text>
</view>
</view>
`
}
- 写样式,考虑到不同手机的适配问题
let unit = ''
wx.getSystemInfo({
success: function (res) {
unit=res.windowWidth/375
},
})
有些宽高需要动态值,所以也用了传参
const style = (nameHeight) => {
return {
container: {
position:'relative',
width: 315*unit,
height: 440*unit,
backgroundColor: '#fff',
flexDirection: 'column',
alignItems:'center',
borderRadius: 8*unit
},
box1: {
width: 283*unit,
height: 159*unit,
marginTop: 20*unit
},
img: {
width: 283*unit,
height: 159*unit,
borderRadius: 4*unit
},
namebox: {
width: 283*unit,
height: nameHeight*unit,
marginTop: 9*unit
},
nametext: {
width: 283*unit,
height: nameHeight*unit,
fontSize: 16*unit,
color: '#000'
},
organizebox: {
width: 283*unit,
height: 16*unit,
marginTop: 8*unit
},
organizetext: {
width: 283*unit,
height: 16*unit,
fontSize: 11,
color: '#8C9098',
verticalAlign: 'middle'
},
code: {
width: 80*unit,
height: 80*unit,
marginTop: 24*unit
},
codeimg: {
width: 80*unit,
height: 80*unit
},
activity: {
width: 86*unit,
height: 20*unit,
marginTop: 8*unit
},
activitytext: {
width: 86*unit,
height: 20*unit,
fontSize: 14,
color: '#333333',
verticalAlign: 'middle'
},
textboxtwo: {
width: 78*unit,
height: 16*unit,
marginTop: 4*unit
},
text: {
width: 78*unit,
height: 16*unit,
fontSize: 11,
color: '#646464',
verticalAlign: 'middle'
}
}
}
- 把定义的元素和样式抛出去
module.exports = {
wxml,
style
}
5.在需要展示海报的地方引入
因为插件里的canvas有一个自己的宽高,所以我们需要把海报的宽高计算好传入
<wxml-to-canvas class="widget" width="{{315*unit}}" height="{{440*unit}}"></wxml-to-canvas>
6.在js页面引入
const { wxml, style } = require('./share.js')
onLoad() {
this.widget = this.selectComponent('.widget')
setTimeout(()=>{
this.renderToCanvas()
},150)
},
renderToCanvas() {
// 海报上动态展示的数据
let name = app.globalData.userInfo.certification ? app.globalData.userInfo.certification.name : app.globalData.userInfo.name
const _wxml = wxml(giftData, name, icon, code)
// 动态样式
let wordwidth = word*12+24
let wordleft = Math.floor((315-wordwidth)/2)
let numWidth = num*22
const _style = style(wordwidth, wordleft,numWidth)
const p1 = this.widget.renderToCanvas({
wxml: _wxml,
style: _style
})
wx.showLoading({
title: '生成中',
})
p1.then((res) => {
this.container = res
}).finally(() => {
wx.hideLoading();
})
},