uniapp或小程序利用canvas生成圆图

2020-06-02 02:44
椰子皮
9188
0
15

在uniapp的.vue文件使用cover-view太难受了,cover-image无法设置成圆角,不得不找个投机取巧的方法,临时写了一下,将就着用吧

废话不说,直接上代码,

首先是html部分

<canvas canvas-id="test" id="test" style="width: 100rpx;height: 100rpx; position: fixed;opacity: 0;"></canvas>
<image :src="testCircleImage" style="width: 100rpx;height: 100rpx" mode="aspectFill"></image>
<image src="/static/img/icon.png" style="width: 100rpx;height: 100rpx" mode="aspectFill"></image>

 

注意canvas-idid都需要写成一样的

 

js部分

import makeCircleImg from '@/utils/makeCircleImg.js'

data() {
  return {
    testCircleImage: ''
  }
},
async onReady() {
  const imgUrl = 'http://localhost/static/img/icon.png'
  this.testCircleImage = await makeCircleImg('test', imgUrl, this)
}

 

函数部分

/**
 * @name 绘制圆角图片
 * @author zzc 2020-4-15
 * @description 由于cover-image无法设置圆角,这里用canvas处理成圆角
 * @param { String } canvasId canvas的id
 * @param { String } src 图片的地址
 * @param { Object } _this Vue实例
 */

export default function(canvasId, src, _this) {
  return new Promise(function (resolve) {
    const ctx = uni.createCanvasContext(canvasId)
    const view = uni.createSelectorQuery().in(_this).select(`#${canvasId}`);
    view.fields({ size: true}, function(data) {
      const avatarWidth = data.width
      const avatarLeft = avatarWidth / 2
      const avatarTop = data.height
      ctx.save()
      ctx.beginPath()
      ctx.arc(avatarWidth / 2, avatarWidth / 2, avatarWidth / 2, 0, Math.PI * 2, false);
      ctx.clip()
      ctx.drawImage(src, 0, 0, avatarWidth, avatarWidth)
      ctx.closePath()
      ctx.restore()
      ctx.draw(false, function() {
        // 返回canvas图片信息
        uni.canvasToTempFilePath({
          canvasId,
          success: function(res) {
            resolve(res.tempFilePath)
          },
          fail: function(err){
            console.log(err)
          }
        })
      })
    }).exec();
  })
}

 

最终效果

支付宝微信
15
关注公众号获取更多内容
vue3.0+typescript使用tinymce富文本编辑器
结合lazyload实现文章页里面的图片预加载
暂无评论,快抢沙发吧
不支持canvas
春季
夏季
秋季
冬季
暗黑
简约
小清新