微信小程序之canvas繪制海報分享到朋友圈


繪制canvas內容

首先,需要寫一個canvas標簽,給canvas-id命名為shareBox

1 <canvas canvas-id="shareBox"></canvas>

其次,我們就要根據需求(效果圖如下)在canvas上面繪制內容了,我這里canvas指的是紅框里面的內容

然后開始繪制內容啦,先定義一個繪制內容的方法:drawImage

 1 drawImage() {
 2     //繪制canvas圖片
 3     var that = this;
 4     console.log(that.data.userInfo);
 5     var qrPath = that.data.qrcode_temp; //小程序碼本地路徑
 6     var imgLogo = that.data.photoTempath; //微信頭像本地路徑
 7     var banner = that.data.banner_temp; //展會bannertu的本地路徑
 8     var bgimg = "/images/bg4@2x.png"; //背景圖
 9    
10     //創建一個canvas對象
11     const ctx = wx.createCanvasContext('shareBox', this);
12 
13     ctx.setFillStyle("white");
14     var canvasWidth = that.data.width; //自適應寬 15     var canvasHeight = that.data.height - that.data.footHeight;  //自適應高 (減去底部高度) 16     
17     console.log(canvasWidth + "--" + canvasHeight)
18     ctx.fillRect(0, 0, canvasWidth, canvasHeight);
19     ctx.drawImage(bgimg, 10, 10, canvasWidth-20, canvasHeight-20);
20 
21     //繪制分享標題
22    
23     ctx.setFontSize(15);
24     ctx.setFillStyle('#000');
25     ctx.setTextAlign('left');
26     ctx.fillText(that.data.userInfo.nickName+"邀請您一起參加", 110, 50, canvasWidth-135);
27     var title = that.data.exhibitionDetail.ExName;
28     if (title.length > 17) {
29       var a = title.substr(0, 17);
30       var b = title.substr(17, title.length);
31       ctx.fillText(a, 110, 70, canvasWidth - 135);
32       ctx.fillText(b, 110, 90, canvasWidth - 135);
33     }else{
34       ctx.fillText(title, 110, 70, canvasWidth - 135);
35     }
36     
37 
38     //繪制標題
39     ctx.setFontSize(15);
40     ctx.setTextAlign('left');
41     ctx.setFillStyle('#000');
42     ctx.fillText(title, 30, 250, canvasWidth - 60);
43     ctx.fillText(title, 30, 250, canvasWidth - 60);
44 
45     //繪制時間
46     ctx.setFontSize(12);
47     ctx.setTextAlign('left');
48     ctx.setFillStyle('#333');
49     var time = that.data.exhibitionDetail.StartTime+"至"+ that.data.exhibitionDetail.EndTime;
50     ctx.fillText(time, 30, 270, canvasWidth - 60);
51 
52     //繪制地點
53     ctx.setFontSize(12);
54     ctx.setTextAlign('left');
55     ctx.setFillStyle('#333');
56     var place = that.data.exhibitionDetail.Place;
57     ctx.fillText(place, 30, 290, canvasWidth - 60);
58 
59     //繪制圓形頭像
60     ctx.save();
61     ctx.beginPath();
62     ctx.arc(65, 65, 35, 0, 2 * Math.PI,false);
63     ctx.setStrokeStyle('#eee')
64     ctx.stroke(); //畫了背景的話要先畫圓在裁剪才能有圓形圖片
65     ctx.clip(); //裁剪
66     ctx.drawImage(imgLogo, 30, 30, 70, 70);
67     ctx.restore();
68 
69 
70     //繪制banner圖
71    // ctx.drawImage(banner, 15, 120, 150, 315);
72 
73     //繪制小程序碼圖
74     //ctx.drawImage(banner, 70, 310, 100, 100);
75 
76     ctx.draw();
77 
78   }

代碼解釋:

  一、關於畫圓形圖片

    這里遇到的問題是: 繪制圓形圖片的時候需要裁剪,一開始我沒有繪制背景,直接裁剪的(就是沒有ctx.stroke()這一步也是能成功的畫出圓形圖片的)。

    之后加了背景圖之后,就無效了,查看了許多資料得知有背景圖的情況下,需要先把圓畫出來,再裁剪才行,就是我上訴代碼中紅色備注中的寫法。

  二、關於網絡圖片的應用

    上述代碼中有注釋寫的是本地路徑,這個本地路徑就是網絡圖片對應的本地臨時路徑,如何拿到本地臨時路徑,得借助小程序內置方法:wx.downloadFile

    用法如下:我這里是下載的用戶頭像,這里的res.temFilePath就是本地臨時路徑了

    注:下載圖片的域名要在小程序后台的downloadFile里面加上才行

 1 var that = this;
 2 wx.downloadFile({
 3       url: that.data.userInfo.avatarUrl,
 4       success: function (res) {
 5         console.log('圖片:' + res.tempFilePath);
 6         that.setData({
 7           photoTempath: res.tempFilePath
 8         })
 9       }
10 })

  三、關於canvas自適應屏幕

    我這里是需要自適應的,一開始我是想着能不能用%來寫寬高,實踐之后發現是不行的,於是在小程序api中找到wx.getSystemInfo方法拿到設備的寬高

var that = this; 
wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        that.setData({
          width: res.windowWidth,
          height: res.windowHeight
        })
      }

    獲取元素高度: 

var that = this;
const query = wx.createSelectorQuery();
query.select('.share-box').boundingClientRect();
query.exec(function (res) {
   that.setData({
      footHeight: res[0].height
   })
   console.log(that.data.footHeight)
})

  四、小程序碼生成

    前端調用后台接口獲取小程序碼,參數:page(小程序碼的跳轉頁面),id(頁面參數)

    生成小程序碼后同樣需要獲取本地臨時路徑才能在canvas中繪制出來,

    注:通過小程序碼進入的頁面,在onload方法里面可以得到一個參數:scene,這個屬性就是生成小程序碼的時候傳的那個頁面參數

上述代碼的實現效果如下:我這里的小程序碼和banner圖暫時沒有,而且數據也是瞎寫的,湊合看吧

canvas轉成圖片保存到相冊  

 1 canvasToImage() {
 2     var that = this; 
 3     //  canvas畫布轉成圖片
 4     wx.canvasToTempFilePath({
 5       quality: 1,
 6       fileType: 'jpg',
 7       canvasId: 'shareBox',
 8       success: function (res) {
 9         wx.hideLoading();
10         console.log('11' + res.tempFilePath);
11         that.setData({
12           img_temp: res.tempFilePath
13         })
14         // wx.previewImage({
15         //   current: res.tempFilePath, // 當前顯示圖片的http鏈接
16         //   urls: [res.tempFilePath] // 需要預覽的圖片http鏈接列表
17         // })
18         wx.saveImageToPhotosAlbum({
19           filePath: res.tempFilePath,
20           success(res) {
21             console.log(res);
22             wx.showModal({
23               title: '',
24               content: '圖片已保存到相冊,趕緊曬一下吧',
25               showCancel: false,
26               confirmText: '好的',
27               confirmColor: '#72B9C3',
28               success: function (res) {
29                 if (res.confirm) {
30                   console.log('用戶點擊確定');
31                 }
32                 that.setData({
33                   visible: false
34                 })
35               }
36             })
37           },
38           fail: function (res) {
39             if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
40               wx.openSetting({
41                 success(settingdata) {
42                   console.log(settingdata)
43                   if (settingdata.authSetting['scope.writePhotosAlbum']) {
44                     that.saveImg(); //保存失敗嘗試再次保存 45                   } else {
46                     console.log('獲取權限失敗,給出不給權限就無法正常使用的提示')
47                   }
48                 }
49               })
50             }
51           }
52         })
53 
54       },
55       fail: function (res) {
56         console.log(res)
57       }
58     }, this)
59   },

這樣就可以把canvas轉成圖片保存在本地了,分享朋友圈在相冊找圖就好了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM