1、圖片透明及旋轉canvas
let ctx = wx.createCanvasContext('shareImg') ctx.drawImage('../../../' + res[0].path, 0, 0, w, h) ctx.save() ctx.globalAlpha = 0.2 ctx.rotate(-15*Math.PI/180)
2、字體加粗小程序
let text = '這是加粗的文本' ctx.fillText(text, 194, 378 + 0.5) ctx.fillText(text, 194 + 0.5, 378) ctx.fillText(text, 194 , 378)
3、文本換行api
this.canvasTextAutoLine('這是換行的文本',ctx,85,467,60,560) /* canvas文字換行 str:要繪製的字符串 ctx:canvas對象 initX:繪製字符串起始x座標 initY:繪製字符串起始y座標 lineHeight:字行高,本身定義個值便可 canvasWidth:畫布的寬度 */ canvasTextAutoLine(str,ctx, initX, initY, lineHeight,canvasWidth) { const arrText = str.split('')//字符串分割爲數組 let currentText = ''// 當前字符串及寬度 let currentWidth for (let letter of arrText) { currentText += letter currentWidth = ctx.measureText(currentText).width if (currentWidth > canvasWidth) { ctx.fillText(currentText, initX, initY) currentText = '' initY += lineHeight } } if (currentText) { ctx.fillText(currentText, initX, initY) } },
4、生成圖片數組
注意:promise
wx.downloadFile({ url: src, success: function (res) { if(res.tempFilePath) { ctx.drawImage(res.tempFilePath, x, y, w, h) } } })
wx.showLoading({ title: '努力生成中...' }) //小程序本地路役圖片 let promise1 = new Promise(function (resolve, reject) { wx.getImageInfo({ src: '../../../images/bg1.png', success: function (res) { resolve(res) }, fail: function (error) { reject(error) }, }) }); //網絡異步請求 let promise2 = new Promise(function (resolve, reject) { api.orderDetail().then(res => { if(res.code == 0) { resolve() } }).catch((error) => { reject(error) }) }); Promise.all([promise1,promise2]).then(result => { let ctx = wx.createCanvasContext('shareImg') ctx.drawImage('../../' + result[0].path, 0, 0, w, h) ctx.save() wx.downloadFile({ url: result[1].pic, success: function (res) { console.log(res) if(res.tempFilePath) { ctx.drawImage(res.tempFilePath, 178, 790, 216, 216) ctx.stroke() //draw的第一個參數爲false表示僅有一個畫布 //第二個參數必定要加定時器,否則會出現生成的圖片黑白 ctx.draw(false, setTimeout(() => { wx.canvasToTempFilePath({ x: 0, y: 0, width: w, height: h, destWidth: w, destHeight: h, canvasId: 'shareImg', success: function (res) { _this.setData({ "finishCreateCanvas": true }) }, fail: function (res) { _this.createCanvasFail() }, complete: function (res) { wx.hideLoading() } }) }, 500))} } },fail: function (error) { //若是有圖片數據請求失敗,在這裏作進一步的處理 _this.createCanvasFail() }, }) }).catch((error) => { //若是有圖片數據請求失敗,在這裏作進一步的處理 _this.createCanvasFail() })
5、生成圖片
生成圖片以前必須保證canvas已經繪製完成,對此在使用wx.canvasToTempFilePath()方法可使用定時器的形式保存爲臨時圖片路徑,代碼已經在上面有所展現。服務器
//生產環境時 記得這裏要加入獲取相冊受權的代碼 wx.saveImageToPhotosAlbum({ filePath: _this.data.prurl, success(res) { wx.showModal({ content: '圖片已保存到相冊,趕忙曬一下吧~', showCancel: false, confirmText: '好噠', confirmColor: '#72B9C3', success: function (res) { if (res.confirm) { console.log('用戶點擊肯定'); } } }) } })