wxml-to-canvas文档: https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/extended/component-plus/wxml-to-canvas.html
- 在小程序 package.json 所在的目录中执行命令安装 npm 包
npm install --save wxml-to-canvas
- 构建 npm
点击开发者工具中的菜单栏:工具 --> 构建 npm - 在json文件中进行配置引入
"usingComponents": {
"wxml-to-canvas": "/miniprogram_npm/wxml-to-canvas"
},
- 在wxml中使用wxml-to-canvas组件
<!-- 图片展示 -->
<view class="paper_content" wx:if="{{tempFilePath}}">
<image
src="{{tempFilePath}}"
mode="heightFix"
style="height:66%;position: relative;z-index: 999; margin-top:20%"
id="canvas_image"
catchtap="hidePaper"
/>
</view>
<!-- canvas节点 -->
<view class="canvas-container">
<wxml-to-canvas id="widget" width="{{shareImgWidth}}" height="{{shareImgHeight}}" />
</view>
- 获取canvas画布dom节点
onLoad() {
this.widget = this.selectComponent('.widget')
}
- 生成海报和临时图片地址
// 点击生成海报按钮
getPaper() {
this.setData({
tempFilePath: null
})
let bg = "xxx.jpg",
qrCode = this.data.qrcodeUrl
wx.showLoading({
title: '加载中',
mask: true
})
this.wxmlToCanvas(bg, qrCode).then(() => {
wx.hideLoading()
}).catch((err)=>{
wx.hideLoading()
})
},
// 生成海报
wxmlToCanvas(bg, qrCode) {
return new Promise((resolve, reject) => {
let style = {
container: {
width: 311,
height: 553,
flexDirection: 'row',
backgroundColor: '#ccc',
},
img: {
width: 311,
height: 553,
position: 'absolute',
},
qrCode: {
width: 83,
height: 83,
position: 'absolute',
right: 16.5,
bottom: 26
}
}
let wxml = `<view class="container">
<image class="img" src="${bg}"></image>
<image class="qrCode" src="${qrCode}"></image>
</view>`
this.renderToCanvas({ wxml, style}).then(res => {
resolve(res)
})
})
},
//渲染成海报
renderToCanvas({ wxml, style }) {
return new Promise((resolve, reject) => {
const p1 = this.widget.renderToCanvas({ wxml, style })
p1.then((res) => {
this.container = res
return this.extraImage(this)
}).then((res) => {
resolve(res)
})
})
},
// 生成临时图片地址
extraImage() {
return new Promise((resolve, reject) => {
const p2 = this.widget.canvasToTempFilePath()
p2.then((res) => {
this.setData({
tempFilePath: res.tempFilePath
})
resolve(res.tempFilePath)
})
})
},