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
| addWatermark(tempFilePath) { return new Promise(async (resolve, reject) => { try { const compressedFilePath = await this.compressImage(tempFilePath);
const imgInfo = await wx.getImageInfo({ src: compressedFilePath, });
const dpr = wx.getSystemInfoSync().pixelRatio + 1; const widthScaled = imgInfo.width * dpr; const heightScaled = imgInfo.height * dpr;
this.data.canvas.width = widthScaled; this.data.canvas.height = heightScaled;
const canvasStyle = `position:fixed;top: 0;width:${imgInfo.width}px;height:${imgInfo.height}px;left:-${imgInfo.width + 100}px;`;
this.setData({ canvasStyle, });
const image = this.data.canvas.createImage(); image.src = compressedFilePath; image.onload = async () => { this.data.ctx.drawImage( image, 0, 0, imgInfo.width, imgInfo.height, 0, 0, widthScaled, heightScaled ); const fontSize = 32; this.data.ctx.font = fontSize + 'px sans-serif'; this.data.ctx.fillStyle = 'rgba(0,0,0,0.3)'; this.data.ctx.fillStyle = 'red'; const nameText = `用户:${this.data.userName}`; const nameTextLength = await this.getCanvasTextLength(nameText); this.data.ctx.fillText( nameText, widthScaled - nameTextLength - 10, fontSize );
wx.canvasToTempFilePath({ destWidth: widthScaled, destHeight: heightScaled, canvas: this.data.canvas, fileType: 'jpg', success: async (res) => { const imgInfo = await wx.getImageInfo({ src: tempFilePath, }); resolve(res.tempFilePath); this.data.ctx.clearRect(0, 0, widthScaled, heightScaled); }, }); }; } catch (error) { console.log('addWatermark Error', error); resolve(tempFilePath); } }); },
|