開始實現之前先上個效果圖
tips 1.網頁圖片需先配置download域名,可透過wx.getImageInfo轉為臨時路徑;
2.個人習慣問題,習慣使用async-await文法,所以需要引進regenerator這個函式庫,使用方式可上網查。
一、封裝通用微信api返回為Promise對象/datas/common.js
// 封裝取得微信圖片資訊。 export const getWxImageInfo = (imgPath) => { return new Promise((resolve, reject) => { wx.getImageInfo({ src: imgPath, success: res => { resolve(res) }, fail: res => { reject (res) } }) })}// 封裝取得節點選擇器資訊export const getSelectQurey = (queryStr) => { return new Promise(resolve => { var query = wx.createSelectorQuery(); query.select(queryStr).boundingClientRect(); query.exec(res => { resolve(res) }) } )}// 封裝把畫布匯出產生指定大小的圖片export const canvasToTempFilePath = (width, height, canvasId, fileType = 'jpg') => { return new Promise((resolve, reject) => { wx.canvasToTempFilePath({ width, height, canvasId, fileType, success: res => { resolve(res) }, fail: res => { reject(res) } }) })}//封裝儲存圖片到系統相簿export const saveImageToPhotosAlbum = (filePath) => { return new Promise((resolve, reject) => { wx.saveImageToPhotosAlbum({ filePath, success: res => { resolve:res) }, fail => { reject(res) } }) })}二、視圖的實現.wxml
<view class=icon-download catchtap=getCanvas>點選產生圖片</view><!-- 二維碼大圖--><view class='shade' wx:if={{isShowCanvas}}> <view class ='qr-code'> <canvas class='qr-canvas' canvas-id=qrCanvas id=qrCanvas></canvas> <view class='qr-btn'> <view class='qr-btn-save' catchtap='saveImageToPhotosAlbumFunc'>儲存圖片,分享到朋友圈</view> <view class='qr-btn-cancel' catchtap=' hideCanvas'>取消</view> </view> </view></view><!-- 二維碼大圖.end -->.wxss
/* 看大圖*/.shade { width: 100%; height: 100%; background-color: rgba(240, 235, 235, 0.5); position: fixed; z-index: 100; top: 0; left : 0;}.qr-code { width: 600rpx; height: 1000rpx; background-color: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* margin: 30rpx auto; */}.qr-canvas { display: block; background-color: #fff; margin: 0 auto; width: 600rpx; height: 900rpx;}.qr-btn { width: 600rpx; height: 100rpx; line-height: 100rpx; margin: 0 auto; font-size: 28rpx; color: #ff; display:color:color:color:color:color: #f; display:color:color:color:color:color: #f; display:color:color:color:color:color: #f; display:color:color:color:color:color: I 月; display 是? #658dc5;}.qr-btn-save { flex: 0 0 500rpx; text-align: center; border-right: 1rpx solid #fff;}.qr-btn-cancel { text-align: center; flex: 0 0 100rpx;}三、創建canvas並儲存到系統相冊tips
商品圖是正方形的,所以這裡商品圖的寬高都用canvas的寬文字不能換行,這裡只是簡單的處理了一下
注意: wx.canvasToTempFilePath(Object object, Object this)這個的使用,文檔有一句話需要注意的:把目前畫布指定區域的內容匯出產生指定大小的圖片。在draw() 回調裡呼叫此方法才能保證圖片匯出成功。
const app = getApp()const regeneratorRuntime = app.globalData.regeneratorRuntimeconstconst util = require('../../utils/util.js')import { getSelectQurey, getWxImageInfo, canToTempFile, PhotosaveImmage, Photosave/Mr. ' datas/common.js'Page({ data: { isShowCanvas: false, // 是否顯示canvas wxaCode: 'https://xxx..jpg', // 商品小程式碼goodsImageUrl: 'https://xxx..jpg', // 商品圖片canvasTempFilePath: '', // canvas匯出產生圖片的暫存路徑}, // 點選顯示要產生的canvas getCanvas(e) { if (!this.data.wxaCode) { util.showToast('二維碼產生失敗'); return; } this.setData({ isShowCanvas: true }, () => { this.createCanvas(); }) }, // 隱藏canvas hideCanvas() { this .setData({ isShowCanvas: false }) }, // 建立canvas async createCanvas() { wx.showLoading({ title: '圖片生成...' }) const _this = this // 建立節點選擇器const res = await getSelectQurey('#qrCanvas'); // canvas的寬高const cvWidth = res[0].width; const cvHeight = res[0].height; const cvSubValue = cvHeight - cvWidth const qrWidth = cvSubValue / 1.5 const qrMargin = (cvSubValue - qrWidth) / 2 const qrX = cvWidth - qrWidth - qrMargin / 2 const qrY = ValueWidth + qrMargin const PathNameY = cvWidwidY = ValueWidth + qrMargin const PathNameY = cvWidwidY = cvPidt cvSt. ''; try { const wxaCode = _this.data.wxaCode; const qrImage = await getWxImageInfo(wxaCode); qrImagePath = qrImage.path } catch (e) { wx.hideLoading(); this.hideCan.(); '二維碼生成失敗'); return; } //商品網路圖片轉臨時路徑let goodsImagePath = '/images/default_goods.png'; const goodsImage = _this.data.goodsImageUrl; if (goodsImage) { const goodsImageRes = await getWxImage(goodsImage);建立canvas var ctx = wx.createCanvasContext('qrCanvas', _this); // 設定背景ctx.setFillStyle('#fff'); ctx.fillRect(0, 0, cvWidth, cvHeight); // 設定商品圖片商品圖寬高是一樣的ctx.drawImage(goodsImagePath, 0, 0, cvWidth, cvWidth); // 設定二維碼圖片ctx.drawImage(qrImagePath, qrX, qrY, qrWidth, qrWidth); // 設定店家名稱const shopName = '我是店家名稱'; ctx.setFillSshopName'black') ctx.setFontSize(16) ctx.setTextAlign('left') ctx.fillText(shopName, 10, shopNameY, cvWidth - qrWidth); // 設定商品名稱文字不能換行,這裡只是簡單的處理了一下const goodsName = '一個名字很長很長的商品就問你怕不怕'; let goodsName1 = ''; let goodsName2 = ''; ctx.setFillStyle('black') ctx.setFontSize(14) ctx.setTextAlign('left') if (goodsName.length <= 10) { ctx.fillText(goodsName, 10, shopNameY + 30, cvWidth - qrrid); else if (goodsName.length > 10 && goodsName.length <= 22) { goodsName1 = goodsName.substring(0, 10); goodsName2 = goodsName.substring(10); ctx.substring(0, 10); goodsName2 = goodsName.substring(10); ctx.bText( , 10, shopNameY + 50, cvWidth - qrWidth); } else { goodsName1 = goodsName.substring(0, 10); goodsName2 = goodsName.substring(10, 22) + '...'; ctx.fillText(goodsName1, 10, 22) + '...'; ctx.fillText(goodsName1, 10, NameY + + 30,NameY + + 30,NameY cvWidth - qrWidth); ctx.fillText(goodsName2, 10, shopNameY + 50, cvWidth - qrWidth); } // 設定提示const tipText = '長按識別小程序,馬上下單! '; ctx.setFillStyle('gray') ctx.setFontSize(8) ctx.setTextAlign('center') ctx.fillText(tipText, cvWidth / 2, cvHeight - 10); // 完成ctx.draw(false, () => { wx.hideLoading(); _this.canvasToTempFilePathFunc(cvWidth, cvHeight, 'qrCanvas') }); }, // 將目前畫布指定區域的內容匯出產生指定大小的圖片async canvasToTempFilePathFunc(cvWidth, cvHeight, qrCanvas) { try { let resmot cvWidth, cv cvWidth, cvHeight, qrCanvas); this.setData({ canvasTempFilePath: res.tempFilePath }); } catch (error) { console.log(error); util.showToast(error.errM); } }, // 將圖片儲存到本機async saveImageToPhotosAlbumFunc( { let res = await saveImageToPhotosAlbum(this.data.canvasTempFilePath); console.log(res); this.hideCanvas(); util.showToast('圖片儲存成功'); } catch (err) { console.log(err); } }})寫得比較簡單,因為主要是方便自己做記錄的,所以也沒有考慮到過多的使用場景。
總結以上所述是小編給大家介紹的微信小程式之html5 canvas繪圖並保存到系統相冊,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回覆大家的!