微信小程序 分享图片使用canvas裁剪按比例生成

wxml:

<canvas type="2d" id="canvas"></canvas>

js:

wx.getImageInfo({
 src:“”, // 这里填写网络图片路径 
  success: (res) => {
    this.clipImage(res.width, res.height)
  }
})
// 裁剪图片
clipImage(imgW, imgH) {
  new Promise((resolve, reject) => {
    let canvasH = imgH;    // 获取图片高度
    let canvasW = imgH * 4 / 5;  // 根据图片高度 获取对应的高度
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas')
      .fields({
        id: true,
        node: true,
        size: true
      })
      .exec(async (res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        canvas.width = canvasW
        canvas.height = canvasH
        let seal = canvas.createImage();
        seal.src = this.data.activityDetail.pic_url;
        seal.onload = () => {
          ctx.drawImage(seal, (imgW - canvasW) / 3, 0, canvas.width * 1.55, canvas.height * 1.55, 0, 0, canvas.width, canvas.height);
          wx.canvasToTempFilePath({
            canvas: canvas,
            success: (res) => {
              this.path = res.tempFilePath  // 转发的图片
              resolve()
            },
            fail(res) {
              console.log(res);
            }
          }, this)
        }
      })
  })
}

微信文档好乱!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用微信小程序Canvas 组件和相关 API 来实现图片裁剪成圆形的效果。以下是一个简单的示例代码: 1. 在你的小程序页面的 JSON 文件中添加 Canvas 组件: ```json { "usingComponents": { "canvas": "/path/to/canvas" } } ``` 2. 在你的小程序页面的 WXML 文件中添加 Canvas 组件的标签: ```html <canvas canvas-id="myCanvas" style="width: 200px; height: 200px;"></canvas> ``` 3. 在你的小程序页面的 JS 文件中编写相关代码: ```javascript Page({ onReady: function () { const ctx = wx.createCanvasContext('myCanvas') wx.getImageInfo({ src: '/path/to/image.jpg', success: function (res) { const imgWidth = res.width const imgHeight = res.height const radius = imgWidth > imgHeight ? imgHeight / 2 : imgWidth / 2 ctx.save() ctx.beginPath() ctx.arc(radius, radius, radius, 0, 2 * Math.PI) ctx.clip() ctx.drawImage(res.path, 0, 0, imgWidth, imgHeight, 0, 0, radius * 2, radius * 2) ctx.restore() ctx.draw() } }) } }) ``` 上述代码中,通过 `wx.getImageInfo` 方法获取图片信息,然后根据图片大小确定裁剪半径。接下来,在 Canvas 上绘制一个圆形路径并使用 `ctx.clip()` 方法进行裁剪。最后,使用 `ctx.drawImage` 方法将图片绘制在裁剪后的区域内。最后调用 `ctx.draw()` 方法进行渲染。 请注意替换示例代码中的图片路径和 Canvas 组件的样式为你实际使用的路径和样式。 希望对你有所帮助!如有任何问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值