WXML 文件
老写法
<canvas canvas-id="canvasPoster" style="width:1000px;height:1500px;"></canvas>
新写法
<canvas type='2d' id="canvasPoster" style="width:1000px;height:1500px;"></canvas>
JS 文件
老接口写法
var that = this; let ctx = wx.createCanvasContext('canvasPoster', this) let canvasW = 1000 // 画布的真实宽度 let canvasH = 1500 //画布的真实高度 let headerW = 48 * this.systemInfo.pixelRatio let qrcodeW = 430 let qrcodeX = (canvasW - qrcodeW)/2 //定位到中间 let qrcodeY = canvasH/14*7 // 填充背景 ctx.drawImage(this.data.bgImg, 0, 0, canvasW, canvasH) ctx.save() ctx.drawImage(this.data.qrcode, qrcodeX, qrcodeY, qrcodeW, qrcodeW) ctx.save() ctx.draw() setTimeout(() => { wx.canvasToTempFilePath({ canvasId: 'canvasPoster', x: 0, y: 0, width: canvasW, height: canvasH, destWidth: canvasW, destHeight: canvasH, success: (res) => { that.setData({ poster: res.tempFilePath, }) } }) }, 200)
新接口写法
var that = this; const query = wx.createSelectorQuery(); query.select('#canvasPoster').fields({node: true, size: true}).exec((res) => { const canvas = res[0].node; canvas.width = 1000 canvas.height = 1500 const ctx = canvas.getContext('2d'); let canvasW = 1000 // 画布的真实宽度 let canvasH = 1500 //画布的真实高度 let qrcodeW = 430 let qrcodeX = (canvasW - qrcodeW)/2 //定位到中间 let qrcodeY = canvasH/14*7 // 填充背景 wx.downloadFile({ url: that.data.bgImg, // 海报URL success: res => { if (res.statusCode == 200){ var _bgImg = res.tempFilePath; wx.downloadFile({ url: that.data.qrcode, // 二维码URL success: res => { if (res.statusCode == 200){ var _qrcode = res.tempFilePath; const bgImg = canvas.createImage(); bgImg.src = _bgImg; bgImg.onload = () => { ctx.drawImage(bgImg, 0, 0, canvasW, canvasH); const qrcode = canvas.createImage(); qrcode.src = _qrcode; qrcode.onload = () => { ctx.drawImage(qrcode, qrcodeX, qrcodeY, qrcodeW, qrcodeW); ctx.save() setTimeout(() => { wx.canvasToTempFilePath({ canvas: canvas, x: 0, y: 0, width: canvasW, height: canvasH, destWidth: canvasW, destHeight: canvasH, success: (res) => { // 生成二维码海报图片 that.setData({ poster: res.tempFilePath, }) } }) }, 200) }; }; } } }); } } }); });