1. 程式人生 > 其它 >uniapp使用canvas繪製兩張圖片合併為一張圖並儲存至手機(H5+小程式)

uniapp使用canvas繪製兩張圖片合併為一張圖並儲存至手機(H5+小程式)

需求: 訪客二維碼圖片, 包含: 1二維碼   2訪客資訊

1、二維碼使用weapp-qrcode外掛生成(canvas)

2、訪客資訊繪製到背景canvas上

3、最後,將二維碼的canvas合併到背景canvas上。

js 部分:

listOwnerVisit(_objData).then((_visits) => {
                    _that.visitInfo = _visits.visits[0];
// 以上為獲取資料介面
// 開始繪製二維碼 drawQrcode({ width:
200, height: 200, canvasId: 'myQrcode', text: this.visitInfo.qrCode, callback: (e) => { uni.canvasToTempFilePath({ x: 0, y:
0, width: 400, height: 400, destWidth: 400, destHeight: 400, canvasId: 'myQrcode', success: (qrcodeTempRes) => {
// 獲取到單二維碼的tempFilePath // 將二維碼的tempFilePath畫到背景canvas上 uni.getSystemInfo({ success: (systemRes) => {
  // 獲取螢幕寬高 做居中用
this.windowWidth = systemRes.windowWidth; this.windowHeight = systemRes.windowHeight; let ctx = uni.createCanvasContext('myBg'); ctx.setFillStyle('#494949'); let topHeight = 0; // 二維碼 ctx.drawImage(qrcodeTempRes.tempFilePath, this.windowWidth/2 - 100, topHeight += 20, 200, 200);// 列表名
  // 以下為二維碼下方要求顯示的文字內容
ctx.setTextAlign('left'); ctx.setFontSize(14); ctx.setFillStyle('#A0A0A0'); ctx.fillText('訪客姓名:', 10, topHeight += 20); ctx.fillText('訪客聯絡方式:', 10, topHeight += 20); ctx.fillText('來訪事由:', 10, topHeight += 20); ctx.fillText('車牌號:', 10, topHeight += 20); ctx.fillText('車輛稽核狀態:', 10, topHeight += 20); ctx.fillText('停車場:', 10, topHeight += 20); ctx.fillText('停車位:', 10, topHeight += 20); ctx.fillText('隨行人數:', 10, topHeight += 20); ctx.fillText('預計來訪時間:', 10, topHeight += 20); ctx.fillText('預計離開時間:', 10, topHeight += 20); ctx.fillText('備註:', 10, topHeight += 20);

  // 繪製最終完整圖
ctx.draw(true, () => { setTimeout(() => { // 獲取到合併後的地址 uni.canvasToTempFilePath({ canvasId: 'myBg', fileType: 'jpg', success: (res2) => { this.tempFilePath = res2.tempFilePath //#ifdef H5 this.needLongTapSaveImg = true; //#endif } }) }) }) } }) } }) } }) })

html部分:

        <view class="u-qrcode" style="text-align: center;">
            <canvas style="width: 200px; height: 200px; margin: 0 auto;background: #fff;visibility: hidden;float: left;" canvas-id="myQrcode"></canvas>
            <canvas style="width: 100%; height: 600px; margin: 0 auto;background: #fff;" canvas-id="myBg" v-show="!needLongTapSaveImg"></canvas>
            <image :src="tempFilePath" style="width: 100%; height: 600px; margin: 0 auto;" v-show="needLongTapSaveImg"></image>
        </view>

1