To use Canvas 2D on wechat, you must use the createImage API. This API is dead, so use another way to implement the poster.

The canvas 2D method recommended by wechat is replaced with the old canvas implementation method that wechat will soon abandon, so the API createImage can be avoided. Other implementation methods and ideas are the same as wechat small program Canvas poster summary -1.

The difference

1. Canvas declaration is different

WXML, no longer declares type=2d, id attribute

<canvas canvas-id="c3" class="canvas1" style="width: {{canvasStyle.width}}rpx; height: {{canvasStyle.height}}rpx;" ></canvas>Copy the code

Js, get the context object

const ctx = wx.createCanvasContext(canvasId);
Copy the code

2. Load the image, avoiding the dead API createImage

Wx. getImageInfo is used to obtain the temporary local path of the image file, which is easy to draw the image by calling ctx.drawImage

wx.getImageInfo({ src: imgUrl, success (res) { resolve(res); }, fail(e) {business.toast.show(' poster image failed to load, please try again later ~', 'none'); reject(e); }})Copy the code

Ctx. draw callback function

To download a canvas drawing, you must call wx.canvastotempFilepath inside the ctx.draw callback to complete the download

ctx.draw(false, async () => { try { const tempPath = await haibaoUtil.createHaibaoUrl(canvasId, this.data.canvasStyle); this.save(tempPath); } catch(e) { console.error(e); Logger. error(' Failed to save poster image, please try again later ~',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); }})}); },Copy the code

The following code

Github.com/guxiansheng…