前言:由于公司目前业务需求,需要一个半圆环形的进度条来展示数据,而市面的组件库暂时不满足当前需求,于是自己使用Canvas实现了一个组件v-circel-ring,并发布于NPM生态。
1. 使用方式
控制台先下载包
npm install v-circle-ring
在main.js入口文件中引入包,并注册
import vCircleRing from 'v-circle-ring'
Vue.use(vCircleRing)
在需要使用的页面中直接使用标签进行使用,如:
<div id="app">
<v-circle-ring :option="options"></v-circle-ring>
</div>
针对配置对象options,在data中进行定义:
data() {
return {
options: {
// 圆环的宽度
width: 300,
// 圆环的高度
height: 300,
// 进度条颜色,支持命名颜色(red、yellow)、16进制(#1479E1)
progressColor: "#1479E1",
// 圆环背景底色,同支持命名颜色和16进制颜色
ringBackgroundColor: "#eee",
// 比例的分子部分
numerator: 176,
// 比例的分母部分
denominator: 200,
// 中间数字颜色,同支持命名颜色和16进制颜色
numColor: '#000',
// 底部文字颜色,同支持命名颜色和16进制颜色
textColor: '#000',
// 中间数字字体大小,单位为px
numFontSize: 16,
// 底部文字字体大小,单位为px
textFontSize: 19,
// 底部文字内容
textContent: '部分 / 全部',
// 圆环的线宽度
lineWidth: 10
}
}
}
简单两部,就可以直接出效果了,如下所示:
2. 实现思路
首先先创建canvas画布:
let canvas = document.getElementById(this.ringContainerId)
再画一个底部的圆环:
function circle(cx, cy, r) {
ctx.beginPath()
ctx.lineWidth = lineWidth
ctx.strokeStyle = backgroundColor
ctx.arc(cx, cy, r, Math.PI * 1, Math.PI * 2)
ctx.stroke()
}
最后是进度条圆环
function sector(cx, cy, r, startAngle, endAngle) {
ctx.beginPath()
ctx.lineWidth = lineWidth
// 进度条颜色
ctx.strokeStyle = progressColor
//圆弧两端的样式
ctx.lineCap = 'round'
//圆弧
ctx.arc(
cx,
cy,
r,
Math.PI * 1,
Math.PI * 1 + (endAngle / 100) * ((Math.PI * 5) / 3),
false
)
ctx.stroke()
}
更多细节可直接down源码看,注释清除,也很简单
最后附上github源码地址:点我获取源码