小程序canvas的使用


現在開發小程序都會有保存圖片到本地,這個保存的圖片我們可以用canvas畫布來畫出這么圖片

 

 

 

我們首先在wxml中觸發點擊事件

          <view bindtap="canvas">
            <text>保存到本地</text>
          </view>
    
<view class="model" hidden="{{canvasHide}}" bindtap="clickhid">
      <canvas canvas-id="Canvas" class="canvas"></canvas>
      <view class="btnsave" catchtap="save">保存到相冊</view>
    </view>

  

  wxss中注入樣式

.model {
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: 99;
  background: rgba(0, 0, 0, 0.7);
  left: 0;
  top: 0;
}

.canvas{
  width: 240px;
  height: 255px;
  position: fixed;
  left: 0;
  right: 0;
  top: 30%;
  z-index: 999;
  margin: 0 auto;
  background: #fff;
}
.btnsave{
  width: 100%;
  height: 60px;
  line-height: 60px;
  background: #FE2B54;
  color: #fff;
  text-align: center;
  position: fixed;
  z-index: 99;
  left: 0;
  bottom: 0;
}

  js中寫入邏輯代碼,如下:

 data:{ 
canvasHide:true, //控制畫布是否顯示
canvasImg:"",
canvasWidth: 140
})
//畫布生成圖片 canvas() {
this.setData({
canvasHide:false,
}) wx.showToast({ title: '分享圖片生成中...', icon: 'loading', duration: 1000 }); var item = { headImg:"https://t8.baidu.com/it/u=3571592872,3353494284&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1586336426&t=06ceca9a464a8b57ba350c632f4a9dfd", cover:"http://img5.imgtn.bdimg.com/it/u=3720661285,1522818110&fm=26&gp=0.jpg", nickName:"微笑時很美n", title:"111111111" }; let promise1 = new Promise(function(resolve, reject) { wx.getImageInfo({ src: item.cover, success: function(res1) { resolve(res1); } }) }); let promise2 = new Promise(function(resolve, reject) { wx.getImageInfo({ src: item.headImg, success: function(res1) { resolve(res1); } }) }); let promise3 = new Promise(function(resolve, reject) { wx.getImageInfo({ src: 'http://img4.imgtn.bdimg.com/it/u=1707295955,795233957&fm=26&gp=0.jpg', success: function(res1) { resolve(res1); } }) }); Promise.all([ promise1, promise2, promise3 ]).then(res1 => { const ctx = wx.createCanvasContext('Canvas', this) //主要就是計算好各個圖文的位置 ctx.setFillStyle('white'); ctx.fillRect(0, 0, 600, 880); // ctx.drawImage(res1[0].path, 0, 0, 240, 135) that.drawImage(ctx, res1[0].path, res1[0].width, res1[0].height); var avatarurl_width = 23.5; //繪制的頭像寬度 var avatarurl_heigth = 23.5; //繪制的頭像高度 var avatarurl_x = 17; //繪制的頭像在畫布上的位置 var avatarurl_y = 145; //繪制的頭像在畫布上的位置 ctx.save(); ctx.beginPath(); //開始繪制 ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false); ctx.clip(); ctx.drawImage(res1[1].path, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推進去圖片,必須是https圖片 ctx.restore(); ctx.drawImage(res1[2].path, 166, 180, 68, 68) ctx.setFontSize(15) ctx.setFillStyle('#000000') ctx.fillText(item.nickName, 50, 163) ctx.setFontSize(12) ctx.setFillStyle('#888888') that.drawText(ctx, (item.title || ''), 193, 10, 110); ctx.setFontSize(9) ctx.setFillStyle('#888888') ctx.fillText('長按識別二維碼,查看新鮮事兒~', 10, 245) ctx.stroke() //繪制圖片 ctx.draw(false, setTimeout(() => { wx.canvasToTempFilePath({ x: 0, y: 0, width: 310, height: 355, destWidth: 310 * 2, destHeight: 355 * 2, canvasId: 'Canvas', fileType: 'png', quality: 1, success: function(res) { that.setData({ canvasImg: res.tempFilePath, }) wx.hideToast() }, fail: function(res) { } }, this) }, 200)); }) }, // 描繪圖片 drawImage(ctx, imgPath, imgWidth, imgHeight) { let cWidth = this.data.canvasWidth; let cHeight = this.data.canvasWidth; let dWidth = cWidth / imgWidth; let dHeight = cHeight / imgHeight; if (imgWidth > cWidth && imgHeight > cHeight || imgWidth < cWidth && imgHeight < cHeight) { if (dWidth > dHeight) { ctx.drawImage(imgPath, 0, (imgHeight - cHeight / dWidth) / 2, imgWidth, cHeight / dWidth, cWidth / 3 + 5, 0, cWidth, cHeight) } else { ctx.drawImage(imgPath, (imgWidth - cWidth / dHeight) / 2, 0, cWidth / dHeight, imgHeight, cWidth / 3 + 5, 0, cWidth, cHeight) } } else { if (imgWidth < cWidth) { ctx.drawImage(imgPath, 0, (imgHeight - cHeight / dWidth) / 2, imgWidth, cHeight / dWidth, cWidth / 3 + 5, 0, cWidth, cHeight) } else { ctx.drawImage(imgPath, (imgWidth - cWidth / dHeight) / 2, 0, cWidth / dHeight, imgHeight, cWidth / 3 + 5, 0, cWidth, cHeight) } } }, //繪制多行文字 drawText: function(ctx, str, initHeight, titleHeight, canvasWidth) { var lineWidth = 0; var lastSubStrIndex = 0; //每次開始截取的字符串的索引 for (let i = 0; i < str.length; i++) { lineWidth += ctx.measureText(str[i]).width; if (lineWidth > canvasWidth) { ctx.setFontSize(14) ctx.setFillStyle('#888888') ctx.fillText(str.substring(lastSubStrIndex, i), 20, initHeight); //繪制截取部分 initHeight += 20; //20為字體的高度 lineWidth = 0; lastSubStrIndex = i; titleHeight += 30; } if (i == str.length - 1) { //繪制剩余部分 ctx.fillText(str.substring(lastSubStrIndex, i + 1), 20, initHeight); } } // 標題border-bottom 線距頂部距離 titleHeight = titleHeight + 10; return titleHeight },

  保存到相冊

  save: function() {
    var that = this
    //生產環境時 記得這里要加入獲取相冊授權的代碼
    wx.saveImageToPhotosAlbum({

      filePath: that.data.canvasImg,
      success(res) {
        wx.showModal({
          content: '圖片已保存到相冊,趕緊曬一下吧~',
          showCancel: false,
          confirmText: '好',
          confirmColor: '#000000',
          success: function(res) {
            if (res.confirm) {
              that.setData({
                canvasHide: false
              })
            }
          }
        })
      }
    })
  },

  


免責聲明!

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



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