json2canvas:使用JSON生成小程序海报
在项目里写过几个canvas生成分享海报页面后,觉得这是个重复且冗余的工作.于是就想有没有能通过类似json直接生成海报的库。 然后就在github找到到两个项目:
-
wxa-plugin-canvas,不太喜欢配置文件的写法,就没多去了解。
-
mp_canvas_drawer,使用方式就比较符合直觉,不过可惜功能有点少。
然后就想着能不能自己再造个轮子。 于是就有了这个项目 json2canvas,你可以简单的理解为是mp_canvas_drawer的增强版吧。
json2canvas canvas绘制海报,写个json就够了
项目的canvas绘制是基于cax实现的,所以天然的带来一个好处,json2canvas同时支持小程序和web
功能
-
支持缩放。 如果设计稿是750,而画布只有375时.你不需要任何换算,只需要将scale设置为0.5即可.
-
支持文本(长文本自动换行,感谢 coolzjy@v2ex 提供的正则 https://regexr.com/4f12l ,优化了换行的计算方式(不会粗暴的折断单词))
-
支持图片(圆角)
-
支持圆型,矩形,矩形圆角
-
支持分组(cax里很好用的一个功能)
-
同时支持小程序和web
示例
web-demo 界面左边的json,可以进行编辑,直接看效果哟~
小程序-demo
|
1
2
|
git clone https://github.com/willnewii/json2canvas.git微信开发者工具导入项目 example/weapp/ |
小程序安装
|
1
2
|
npm i json2canvas微信开发者工具->工具->构建npm |
在需要使用的界面引入Component
|
1
2
3
4
5
|
{"usingComponents": {"json2canvas":"/miniprogram_npm/json2canvas/index" }} |
效果图
想要生成一个这样的海报,需要怎么做? (红框是图片元素,蓝框是文字元素,其余的是一张背景图。 ) 一个json就搞定.具体支持的元素和参数,请查看项目readme
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
{"width": 750,"height": 1334,"scale": 0.5,"children": [ {"type": "image","url": "http://res.mayday5.me/wxapp/wxavatar/tmp/bg_concerts_1.jpg","width": 750,"height": 1334 }, {"type": "image","url": "http://res.mayday5.me/wxapp/wxavatar/tmp/wxapp_code.jpg","width": 100,"x": 48,"y": 44,"isCircular": true, }, {"type": "circle","r": 50,"lineWidth": 5,"strokeStyle": "#CCCCCC","x": 48,"y": 44, }, {"type": "text","text": "歌词本","font": "30px Arial","color": "#FFFFFF","x": 168,"y": 75,"shadow": {"color": "#000","offsetX": 2,"offsetY": 2,"blur": 2 } }, {"type": "image","url": "http://res.mayday5.me/wxapp/wxavatar/tmp/medal_concerts_1.png","width": 300,"x": "center","y": 361 }, {"type": "text","text": "一生活一场 五月天","font": "38px Arial","color": "#FFFFFF","x": "center","y": 838,"shadow": {"color": "#000","offsetX": 2,"offsetY": 2,"blur": 2 } }, {"type": "text","text": "北京6场,郑州2场,登船,上班,听到你想听的歌了吗?","font": "24px Arial","color": "#FFFFFF","x": "center","y": 888,"shadow": {"color": "#000","offsetX": 2,"offsetY": 2,"blur": 2 } }, {"type": "rect","width": 750,"height": 193,"fillStyle": "#FFFFFF","x": 0,"y": "bottom" }, {"type": "image","url": "http://res.mayday5.me/wxapp/wxavatar/tmp/wxapp_code.jpg","width": 117,"height": 117,"x": 47,"y": 1180 }, {"type": "text","text": "长按识别小程序二维码","font": "26px Arial","color": "#858687","x": 192,"y": 1202 }, {"type": "text","text": "加入五月天 永远不会太迟","font": "18px Arial","color": "#A4A5A6","x": 192,"y": 1249 }] } |

浙公网安备 33010602011771号