微信小程序分享时,封面图片裁剪为5:4

微信小程序分享时,封面图片裁剪为5:4

直接贴代码:

//裁剪分享的图片为5:4
//传入图片地址
  cutShareImg:function(imgurl){
    let that=this;
    wx.getImageInfo({
      src: imgurl,  // 这里填写网络图片路径 
      success: (res) => {
        let ctx = wx.createCanvasContext('canvas');  
        let canvasW = 640, canvasH = res.height;
        if (res.width / res.height > 5 / 4) { // 长宽比大于5:4
          canvasW = res.height * 5 / 4;
        }
        ctx.drawImage(res.path, (res.width - canvasW) / 2, 0, canvasW, canvasH, 0, 0, canvasW, canvasH)
        ctx.draw(false, () => {
            wx.canvasToTempFilePath({
              width: canvasW,
              height: canvasH,
              destWidth: canvasW,
              destHeight: canvasH,
              canvasId: 'canvas',
              fileType: 'jpg',
              success: (res) => {
              	//设置分享图片路径
                that.setData({
                  shareimg:res.tempFilePath
                });
              }
            })
        })
      }
    });
  },

html代码

<!-- 裁剪分享时图片的canvas -->
<canvas style="position: absolute; top: -1000px; left: -1000px; width: 640px; height: 640px; background: #000;" canvas-id="canvas"></canvas>

分享的时候

onShareAppMessage: function () {
	return {
		title: title,
		desc: '',
		path: '',
		imageUrl: this.data.shareimg,
	}
}

当然还需要配置小程序downloadFile合法域名,及图片路径的域名

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值