当前位置:   article > 正文

canvas绘制圆形进度条_小程序圆形进度条怎么做

小程序圆形进度条怎么做

canvas绘制圆形进度条

用canvas绘制了一个圆形进度条,记录一下:
效果如下:请添加图片描述

感觉效果还行,不过有待优化
代码如下:
我是用Vue写的

组件的代码:

progressCanvas.vue

<template>
  <div>
  	<canvas id="progressCanvas" width="200" height="200"></canvas>
  </div>
</template>

<script>
export default {
  name: 'ProgressCanvas',
  data() {
    return {
      drawPgress: 0
    }
  },

  mounted() {

    const aa = setInterval(() => {
      this.drawProgress(this.drawPgress += 0.01)	// 传入一个0到1之间的数字来表示进度
      if (this.drawPgress > 1) {
        clearInterval(aa)
      }
    }, 100)

    // this.drawProgress(0.8)
  },

  methods: {
    drawProgress(progress) {
      const canvas = document.getElementById('progressCanvas')
      if (canvas.getContext) {
        const ctx = canvas.getContext('2d')
        const x = canvas.width / 2
        const y = canvas.height / 2
        const radius = 90
        const startAngle = -0.5 * Math.PI // 从顶部开始
        const endAngle = (-0.5 + 2 * progress) * Math.PI

        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)

        // 绘制圆形进度条背景
        ctx.beginPath()
        ctx.arc(x, y, radius, 0, 2 * Math.PI)
        ctx.lineWidth = 10
        ctx.strokeStyle = '#5D52E1'
        ctx.stroke()

        // 计算渐变色的起始和结束坐标
        const gradientStartX = x + radius * Math.cos(startAngle)
        const gradientStartY = y + radius * Math.sin(startAngle)
        const gradientEndX = x + radius * Math.cos(endAngle)
        const gradientEndY = y + radius * Math.sin(endAngle)

        // 创建渐变色
        const gradient = ctx.createLinearGradient(gradientStartX, gradientStartY, gradientEndX, gradientEndY)
        gradient.addColorStop(0, '#5D52E1')
        gradient.addColorStop(1, '#FFFFFF')

        // 绘制圆形进度条
        ctx.beginPath()
        ctx.arc(x, y, radius, startAngle, endAngle)
        ctx.lineWidth = 10
        ctx.strokeStyle = gradient
        ctx.stroke()
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

OK,实现完毕!如果大家有什么更好的想法可以交流一下

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/269482
推荐阅读
相关标签
  

闽ICP备14008679号