canvas实现静态环形进度条(学习用)

效果图

在这里插入图片描述

页面

<template>
  <view>
    <canvas canvas-id="chartBox1" id="chartBox1" class="chart"></canvas>
  </view>
</template>

<script>
import { CircleBox } from './chart.js'
export default {
  data() {
    return {
      cbox1: null //画布实例对象
    }
  },
  onReady() {
    this.initCircle1()
  },
  methods: {
    initCircle1() {
      //实例对象
      this.cbox1 = new CircleBox(uni.createCanvasContext('chartBox1'))
      //开始绘制
      this.cbox1.drawCircle()
    }
  }
}
</script>
<style lang="scss" scoped>
.chart {
  width: 300rpx;
  height: 300rpx;
  margin: 0 auto;
  background: skyblue;
}
</style>

chart.js

export class CircleBox {
  constructor(_context) {
    this.ctx = _context
    //直径
    this.radius = uni.upx2px(300)
    //四周内填充
    this.padding = uni.upx2px(20)
    //圆环宽度
    this.lineWidth = uni.upx2px(20)
    //圆球宽度
    this.lineWidth2 = uni.upx2px(30)
    //圆环颜色
    this.lineColor = 'grey'
    //当前百分比
    this.percent = 0.25
    //进度条颜色
    this.percentLineColor = '#FB8F23'
    //字体大小
    this.fontSize = uni.upx2px(42)
    //字段颜色
    this.fontColor = '#FB8F23'
  }
  drawCircle() {
    this.ctx.clearRect(0, 0, this.radius, this.radius)
    //计算实际半径
    let _radius = this.radius / 2 - this.padding - this.lineWidth
    //开始绘制圆环
    this.ctx.beginPath()
    this.ctx.lineCap = 'round'
    this.ctx.arc(this.radius / 2, this.radius / 2, _radius, -(Math.PI * 1.25), Math.PI * 1.5 - Math.PI * 1.25, false)
    this.ctx.lineWidth = this.lineWidth
    this.ctx.strokeStyle = this.lineColor
    this.ctx.stroke()
    //绘制进度条部分
    this.ctx.beginPath()
    this.ctx.lineCap = 'round'
    this.ctx.arc(this.radius / 2, this.radius / 2, _radius, -(Math.PI * 1.25), Math.PI * 1.5 * this.percent - Math.PI * 1.25, false)
    this.ctx.strokeStyle = this.percentLineColor
    this.ctx.stroke()
    // 绘制圆球
    this.ctx.beginPath()
    this.ctx.lineWidth = this.lineWidth2
    this.ctx.arc(
      this.radius / 2,
      this.radius / 2,
      _radius,
      Math.PI * 1.5 * this.percent - Math.PI * 1.25,
      Math.PI * 1.5 * this.percent - Math.PI * 1.25,
      false
    )
    this.ctx.strokeStyle = 'red'
    this.ctx.stroke()
    //恢复之前保存的绘图上下文
    this.ctx.restore()
    this.ctx.draw()
    return
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值