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>

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

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 03:10:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 03:10:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 03:10:02       82 阅读
  4. Python语言-面向对象

    2024-03-18 03:10:02       91 阅读

热门阅读

  1. SpringBoot3框架,入门学习

    2024-03-18 03:10:02       30 阅读
  2. 【每日前端面经】2024-03-17

    2024-03-18 03:10:02       31 阅读
  3. Linux磁盘分区————逻辑卷

    2024-03-18 03:10:02       35 阅读
  4. 什么是大Key问题

    2024-03-18 03:10:02       47 阅读
  5. HarmonyOS系统开发ArkTS基础编程语法

    2024-03-18 03:10:02       42 阅读
  6. 空回滚和业务悬挂

    2024-03-18 03:10:02       45 阅读