小程序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 {
   100%;
  height: 100%;
  position: fixed;
  z-index: 99;
  background: rgba(0, 0, 0, 0.7);
  left: 0;
  top: 0;
}

.canvas{
   240px;
  height: 255px;
  position: fixed;
  left: 0;
  right: 0;
  top: 30%;
  z-index: 999;
  margin: 0 auto;
  background: #fff;
}
.btnsave{
   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, 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
              })
            }
          }
        })
      }
    })
  },

  

原文地址:https://www.cnblogs.com/BySee1423/p/12613897.html