uniapp使用canvas写环形进度条

20 篇文章 0 订阅
6 篇文章 0 订阅

遇到的坑

  1. 使用普通canvas需要延迟设置draw() stroke()才生效。
  2. 使用canvas2d在微信小程序的开发者工具上表现为固定在屏幕上,不随容器滚动,但是手机表现正常。
  3. 记住: 在组件中获取实例需要使用in(this)。如 const ctx = uni.createCanvasContext('myCanvas',this) const query = uni.createSelectorQuery().in(this)
    在这里插入图片描述

组件代码

<template>
  <div class="com-container">
    <canvas canvas-id="canvas" id="canvas" class="my-canvas" type="2d"></canvas>
  </div>
</template>

<script>
export default {
  props: {
    progress: {
      type: Number,
      default: 50
    },
    innerText: {
      type: String,
      default: '850'
    }
  },
  data() {
    return {
      ctx: null // 画布实例
    }
  },
  mounted() {
    this.getCanvas()
  },
  methods: {
    /**
     * @method 获取画布
     */
    getCanvas() {
      const query = uni.createSelectorQuery().in(this)
      query.select('#canvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node
          canvas.width = 120
          canvas.height = 120
          const ctx = canvas.getContext('2d')
          this.ctx = ctx
        })
      setTimeout(() => {
        this.drawTrack()
        this.drawProgress(this.progress)
        this.drawText(this.innerText)
      }, 500);
    },
    // 绘制轨道
    drawTrack() {
      this.ctx.save()
      this.ctx.beginPath()
      this.ctx.lineCap = "round"
      this.ctx.lineWidth = 8
      this.ctx.strokeStyle = "#dde1ed"
      // x坐标,y坐标,半径,起始角,结束角,顺时针/逆时针
      this.ctx.arc(60, 60, 50, 0, 2 * Math.PI)
      this.ctx.stroke()
      this.ctx.closePath()
      this.ctx.restore()
    },
    // 绘制进度
    drawProgress(num) {
      this.ctx.save()
      this.ctx.beginPath()
      this.ctx.lineCap = "round"
      this.ctx.lineWidth = 8
      this.ctx.strokeStyle = "#5f94f0"
      // context.arc(x,y,r,sAngle,eAngle,counterclockwise);   //x坐标,y坐标,半径,起始角,结束角,顺时针/逆时针
      this.ctx.arc(
        60,
        60,
        50,
        -Math.PI / 2,
        -Math.PI / 2 + ((2 * num) / 100) * Math.PI,
        true
      )
      this.ctx.stroke()
      this.ctx.closePath()
      this.ctx.restore()
    },
    // 绘制文字
    drawText(num) {
      this.ctx.save()
      this.ctx.fillStyle = "#6094F3"
      this.ctx.font = "33px Helvetica"
      this.ctx.textAlign = "center"
      this.ctx.fillText(num, 60, 70)
      this.ctx.restore()
    }
  }
}
</script>

<style lang='scss' scoped>
.com-container {
  width: 240rpx;
  height: 240rpx;

  .my-canvas {
    width: 100%;
    height: 100%;
    z-index: 999;
  }
}
</style>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值