一 、需求
從數據庫中讀取頭像,姓名電話等信息,當分享給女朋友時,每個信息不一樣
二、實現方案
1、先將數據庫中需要的頭像姓名信息讀取出來加載到data 數據項中
data:{firstName:'', // 姓名img:'', // 頭像shareImage:'',// 存儲臨時圖片
}
2、當進入頁面時,就產生圖片,分享時直接分享 在小程序onLoad函數中實現
// 生成分享圖片generateShareImage() {// 進入頁面就下載頭像到臨時地址中const imgUrl = app.globalData.base_url +'uploads/lawyer/'+this.data.imgwx.downloadFile({url: imgUrl,success: (res) => {if (res.statusCode === 200) {// 下載成功,獲取臨時路徑const tempFilePath = res.tempFilePath;console.log("666"+tempFilePath)// 開始繪制 注意這里this.drawPoster(tempFilePath);}},fail: (err) => {console.error('圖片下載失敗:', err);}});},// 繪制海報drawPoster(avatarPath){// createCanvasContext 繪制方法const ctx = wx.createCanvasContext('shareCanvas');// 繪制背景圖(可以是本地或網絡路徑)const bgImagePath = '/images/sharebg.jpg'; // 替換為你的背景圖地址// 1. 繪制背景圖ctx.drawImage(bgImagePath, 0, 0, this.data.canvasWidth, this.data.canvasHeight);// 2. 設置字體樣式ctx.setFontSize(10);ctx.setFillStyle('black');// 3. 繪制姓名頭像if(avatarPath){ctx.save()ctx.arc(40, 30, 11 * 2, 0, 2 * Math.PI) // 圓形邊框//ctx.strokeStyle = '#1A1A1A' // 設置繪制圓形邊框的顏色ctx.stroke() // 繪制出圓形,默認為黑色,可通過 ctx.strokeStyle = '#FFFFFF',設置想要的顏色ctx.clip()ctx.drawImage(avatarPath, 8, 6, 70, 70) // 圖像大小ctx.restore()}// ctx.fillText(`${this.data.firstName}`, 100, 50);drawMultiLineText(ctx,`${this.data.firstName}`,80,28,50, 14, 14);drawMultiLineText(ctx,`${this.data.title}`,80,45,50, 14, 10);// ctx.fillText(`${this.data.mobilePhoneNumber}`, 10, 90);drawMultiLineText(ctx,`${this.data.mobilePhoneNumber}`,35,70,100, 14, 10);// ctx.fillText(`${this.data.email}`,10,110);drawMultiLineText(ctx,`${this.data.email}`,35,90,110, 14, 10);drawMultiLineText(ctx,`${this.data.address_details}`,35,109,90, 16, 10);// 5. 繪制完成ctx.draw(false, () => {// 6. 將 Canvas 導出為臨時圖片路徑wx.canvasToTempFilePath({canvasId: 'shareCanvas',success: (res) => {// res.tempFilePath 是生成的臨時圖片路徑console.log(this.data.mobilePhoneNumber)this.setData({shareImage: res.tempFilePath});// 觸發分享this.onShareAppMessage();},fail: (err) => {wx.showToast({ title: '生成圖片失敗', icon: 'none' });}});});},
onLoad(options){// 調用繪制方法this.generateShareImage()
}
3、分享圖片
onShareAppMessage 觸發分享
onShareAppMessage() {return {title:'標題',//標題path: '/pages/index/index',//路徑imageUrl: this.data.shareImage//圖片}}