小程序解决图片分享裁剪5:4问题

1、解决小程序中分享默认比率5:4导致图片被裁剪;

        为保持图片完整性使用下列方法:

在获取完图片后调用 function cutshareImf(url){} url:为需要处理的图片地址;

wx.js

//传入图片地址
cutShareImg(doctorImg){
    let that=this;
    wx.getImageInfo({
      src: doctorImg,  // 这里填写网络图片路径 
      success: (res) => {
        var data = res
        console.log(res)
        wx.createSelectorQuery()
        .select('#myCanvas') // 在 WXML 中填入的 id
        .fields({ node: true, size: true })
        .exec((res) => {
           // Canvas 对象
           console.log(res)
          const canvas = res[0].node
          // 渲染上下文
          const ctx = canvas.getContext('2d')
          let {width, path, height} = data
          // Canvas 画布的实际绘制宽高
          var widths = height*5/4
          const dpr = wx.getWindowInfo().pixelRatio
          var w = (widths-width)/2
          canvas.width = widths * dpr
          canvas.height = height * dpr
          ctx.scale(dpr, dpr)
          ctx.clearRect(0, 0, widths, height)
          // 图片对象
          const image = canvas.createImage()
          console.log(image)
          image.onload = () => {
            // 将图片绘制到 canvas 上
            ctx.drawImage(image, w, 0)
            wx.canvasToTempFilePath({
                canvas,
                success: res => {
                    // 生成的图片临时文件路径
                    const tempFilePath = res.tempFilePath
                    that.setData({shareimg: tempFilePath})
                },
              })
          }
          image.onerror = (err) => {
                console.log(err)
            }
          image.src= path
          // 生成图片
         
        })
      }
    });
  },

video.wxml

<canvas style="position: absolute; top: -1000px; left: -1000px; width: 640px; height: 640px; background: #000;" type='2d' id="myCanvas"></canvas>

分享时调用shareimg为分享图片的地址

注意:图片过大的时候导致界面画布加载过长导致微信小程序卡死情况;

        可以对下载的图片进行等比缩放使他画布大小变小

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌新芽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值