小程序

微信小程序转发分享,封面图片自定义5:4

2020-07-08  本文已影响0人  躺希腊额阿毛

小程序转发,图片不配置会自动截取顶部页面。如配置图片,比例不为5:4则会截取图片顶部内容。

为使自定义图片完整展示,做了以下操作。

wxml

<!-- width设置了canvasW,height设置了canvasH,换过其他值,好像有影响,background无效 -->
<canvas style="position: absolute; top: -1000px; left: -1000px; width: 875px; height: 700px; background: #fff;" canvas-id="canvas"></canvas>

js

 onShareAppMessage: async function() {
   let imgUrl = 'xxxxx'
    return {
      title: '分享',
      path: `/pages/index/index`,
      imageUrl: await cutShareImg(imgUrl)
    }
  }

方法

const cutShareImg = (imgUrl) => {
  return new Promise((resolve) => {
    wx.getImageInfo({
      src: imgUrl, // 原图路径
      success: (res) => {
        let ctx = wx.createCanvasContext("canvas")
        let canvasW = 0
        let canvasH = res.height
        // 把比例设置为 宽比高 5:4
        canvasW = (res.height * 5) / 4
        // 为画框设置背景色,注意要放在画图前,图会覆盖在背景色上
        ctx.fillStyle = "#fff"
        ctx.fillRect(0, 0, canvasW, canvasH)
        // ctx.drawImage(res.path, (res.width - canvasW) / 2, 0, canvasW, canvasH, 0, 0, canvasW, canvasH)
        ctx.drawImage(
          res.path,
          0,
          0,
          canvasW,
          canvasH,
          (canvasW - res.width) / 2, // 宽度从中间向两边填充
          0,
          canvasW,
          canvasH
        )
        ctx.draw(false, () => {
          wx.canvasToTempFilePath({
            width: canvasW,
            height: canvasH,
            destWidth: 750, // 标准的iphone6尺寸的两倍,生成高清图
            destHeight: 600,
            canvasId: "canvas",
            fileType: "jpg",  // 注意jpg默认背景为透明
            success: (res) => {
              // 设置分享图片路径
              resolve(res.tempFilePath)
            },
          })
        })
      }
    })
  })
}

export default {
  cutShareImg,
}


注:

1.jpg,png背景色,png支持透明色
2.异步方法,最好是在进入页面就调用,否则需要await才行
3.注意canvas的宽高

参考:

微信小程序分享时,封面图片裁剪为5:4
小程序官网
jpg 与 png 的区别

上一篇 下一篇

猜你喜欢

热点阅读