step 1:下载源代码
直接通过 git 下载 wxa-plugin-canvas 源代码。
https://github.com/jasondu/wxa-plugin-canvas
step 2:将miniprogram_dist目录拷贝到自己的项目组件目录中
miniprogram\components\miniprogram_dist
step 3:页面引入该组件:
miniprogram/pages/my/UserPosterQrCodeService/index.json
{
"usingComponents": {
"poster": "/components/miniprogram_dist/poster/index"
}
}
step 4:在 wxml 中使用组件
miniprogram/pages/my/UserPosterQrCodeService/index.wxml
<poster id="poster" config="{{posterConfig}}" bind:success="onPosterSuccess" bind:fail="onPosterFail">
<button>点击生成海报</button>
</poster>
step 5:添加配置信息posterConfig
(1)图片的域名添加到downloadFile合法域名中(开发设置-服务器域名-downloadFile合法域名)
登陆微信公众平台https://mp.weixin.qq.com,输入小程序的登陆邮件和密码,需用管理员微信扫码完成登陆,否则会提示“没有配置权限”。
选择开发-》开发设置-》开始配置,配置https域名
(2)在data中添加配置信息posterConfig
miniprogram/pages/my/UserPosterQrCodeService/index.js
data: {
url: '',
winWidth: 0,
winHeight: 0,
oneHeight: 0, // 风景图的高度
ewmWidth: 0, //二维码的高度
oneWidth: 0, //左右两边的空白
twoWidth: 0, //二维码和边框之间的距离
fontHeight: 0,
text1: '',
text2: '',
text3: '',
text4: '',
posterConfig: {
width: 750,
height: 1000,
backgroundColor: '#fff',
debug: false,
blocks: [
{
x: 0,
y: 10,
width: 750, // 如果内部有文字,由文字宽度和内边距决定
height: 120,
paddingLeft: 0,
paddingRight: 0,
borderWidth: 10,
borderColor: 'red',
backgroundColor: 'blue',
borderRadius: 40,
text: {
text: [
{
text: '金额¥ 1.00',
fontSize: 80,
color: 'yellow',
opacity: 1,
marginLeft: 50,
marginRight: 10,
},
{
text: '金额¥ 1.00',
fontSize: 20,
color: 'yellow',
opacity: 1,
marginLeft: 10,
textDecoration: 'line-through',
},
],
baseLine: 'middle',
},
}
],
texts: [
{
x: 0,
y: 180,
text: [
{
text: '长标题长标题长标题长标题长标题长标题长标题长标题长标题',
fontSize: 40,
color: 'red',
opacity: 1,
marginLeft: 0,
marginRight: 10,
width: 200,
lineHeight: 40,
lineNum: 2,
},
{
text: '原价¥ 1.00',
fontSize: 40,
color: 'blue',
opacity: 1,
marginLeft: 10,
textDecoration: 'line-through',
},
],
baseLine: 'middle',
},
{
x: 10,
y: 330,
text: '金额¥ 1.00',
fontSize: 80,
color: 'blue',
opacity: 1,
baseLine: 'middle',
textDecoration: 'line-through',
},
],
images: [
{
url: 'http://weixin.usdotnet.com/imgage/bgk_wanjiale.jpg',
width: 300,
height: 300,
y: 450,
x: 0,
// borderRadius: 150,
// borderWidth: 10,
// borderColor: 'red',
},
{
url: 'http://weixin.usdotnet.com/imgage/bgk_wanjiale.jpg',
width: 100,
height: 100,
y: 450,
x: 400,
borderRadius: 100,
borderWidth: 10,
},
],
lines: [
{
startY: 800,
startX: 10,
endX: 300,
endY: 800,
width: 5,
color: 'red',
}
]
}
},
step 6:添加生成事件处理函数
onPosterSuccess(e) {
const { detail } = e;
wx.previewImage({
current: detail,
urls: [detail]
})
},
onPosterFail(err) {
console.error(err);
}
异步生成海报步骤
(1)在 wxml 中
<button bindtap="onCreatePoster">异步生成海报</button>
(2)在js中
/**
* 异步生成海报
*/
import Poster from '../../../components/miniprogram_dist/poster/poster';
/**
* 异步生成海报
*/
onCreatePoster() {
Poster.create();
},
组件原理说明文章
https://juejin.im/post/5b7e48566fb9a01a1059543f
使用案例