在項目里寫過幾個canvas生成分享海報頁面后,覺得這是個重復(fù)且冗余的工作.于是就想有沒有能通過類似json直接生成海報的庫.
然后就在github找到到兩個項目:
然后就想著能不能自己再造個輪子.于是就有了這個項目 json2canvas,你可以簡單的理解為是mp_canvas_drawer的增強版吧.
項目的canvas繪制是基于cax實現(xiàn)的.所以天然的帶來一個好處,json2canvas同時支持小程序和web
git clone https://github.com/willnewii/json2canvas.git
微信開發(fā)者工具導(dǎo)入項目 example/weapp/
npm i json2canvas
微信開發(fā)者工具->工具->構(gòu)建npm
在需要使用的界面引入Component
{
"usingComponents": {
"json2canvas":"/miniprogram_npm/json2canvas/index"
}
}
想要生成一個這樣的海報,需要怎么做?(紅框是圖片元素,藍框是文字元素,其余的是一張背景圖。)
一個json就搞定.具體支持的元素和參數(shù),請查看項目readme
{
"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
}]
}