Method: Use wxml-to-canvas to generate images, share the generated images
wxml-to-canvas document: https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/en/extended/component-plus/ wxml-to-canvas.html
1. Install wxml-to-canvas
npm install --Save. wxml-to-canvas
2. Introduce wxml-to-canvas in the required route in page.js
{
"path": "pages/index",
"style": {
"navigationBarTitleText": "自定义分享",
"navigationStyle": "custom",
"usingComponents": {
"wxml-to-canvas": "/wxcomponents/wxml-to-canvas/index"
}
}
},
3. Use it on the sharing page
<wxml-to-canvas id="widget" class="widget" width="300" height="300" style="left:-900%;top:-900%;position: absolute;"></wxml-to-canvas>
<u-button open-type="share" color="linear-gradient(0deg,#58c395 0%, #4daf8b)">分享按钮</u-button>
4. Custom sharing method
async onShareAppMessage (res) {
const cw = 140
const ch = 112
const widget = this.selectComponent('#widget')
const cre = await widget.renderToCanvas({
wxml:`
<view class="view">
<image src="../../static/daifu.jpg" class="bg"></image>
<text class="text">¥${
(this.orderdetail.should_pay/1000).toFixed(2)}元</text>
</view>
`,
style:{
view:{
width:cw,
height:ch,
display: 'flex',
textAlign: 'center',
},
bg:{
position:'absolute',
width:cw,
height:ch,
top:0,
left:0,
},
text: {
fontSize: 9,
fontWeight: 600,
color: '#333',
verticalAlign: 'middle',
top:57,
}
}
})
const re=await widget.canvasToTempFilePath()
return {
title:'支付分享',
path: 'pages/center/pay_type?sharecode=' + this.orderdetail._id, // 打开分享跳转地址
imageUrl:re.tempFilePath,
success: function (res) {
// 回调函数已经取消了,运行时进入不到这里
if(res.errMsg == 'shareAppMessage:ok'){
console.log("分享成功",res)
}
},
fail:function(res){
// 回调函数已经取消了,运行时进入不到这里
console.log("分享失败",res)
}
}
}
5. Sharing effect