微信小程序canvas畫海報總結-2
發表時(shí)間:2021-1-8
發布人(rén):融晨科技
浏覽次數:31
坑爹的(de)微信,使用canvas 2D的(de)方式, 必須用createImage這(zhè)個(gè)API,偏偏這(zhè)個(gè)API挂了(le/liǎo),所以(yǐ)下面使用另一種方式實現海報.
主要(yào / yāo)由微信推薦的(de)canvas 2D方式更換爲(wéi / wèi)微信即将遺棄的(de)老canvas實現方式,因此能夠避免使用createImage這(zhè)個(gè)API.其他(tā)的(de)實現方式和(hé / huò)思路是(shì)和(hé / huò)微信小程序canvas畫海報總結-1一樣的(de).
不(bù)同之(zhī)處
1. canvas聲明方式不(bù)同
wxml, 不(bù)再聲明type=2d, id屬性
<canvas canvas-id="c3" class="canvas1" style="width: {{canvasStyle.width}}rpx; height: {{canvasStyle.height}}rpx;"></canvas>
複制代碼
js, 獲取context對象
const ctx = wx.createCanvasContext(canvasId);
複制代碼
2. 加載圖片,避開createImage這(zhè)個(gè)挂掉的(de)API
主要(yào / yāo)用wx.getImageInfo獲取到(dào)圖片文件的(de)臨時(shí)本地(dì / de)路徑,便于(yú)調用ctx.drawImage畫圖片
wx.getImageInfo({
src: imgUrl,
success (res) {
resolve(res);
},
fail(e) {
business.toast.show('海報圖片加載失敗,請稍後重試~', 'none');
reject(e);
}
})
複制代碼
3.ctx.draw回調函數
要(yào / yāo)下載canvas畫出(chū)來(lái)的(de)圖片,就(jiù)必須在(zài)ctx.draw的(de)回調函數内調用wx.canvasToTempFilePath,最終完成下載
ctx.draw(false, async () => {
try {
const tempPath = await haibaoUtil.createHaibaoUrl(canvasId, this.data.canvasStyle);
this.save(tempPath);
} catch(e) {
console.error(e);
logger.error('保存海報圖片失敗, 請稍後重試~',e);
}
});
createHaibaoUrl(canvasId, canvasStyle) {
return new Promise((resolve, reject) => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: this.computedWAndD(canvasStyle.width),
height: this.computedWAndD(canvasStyle.height),
destWidth: canvasStyle.width*3,
destHeight: canvasStyle.height*3,
canvasId: canvasId,
fileType: 'png',
success(res) {
resolve(res.tempFilePath);
},
fail(error) {
reject(error);
}
})
});
},
複制代碼