function DrawCircle (opts) {
var node = opts.node
if (!node) return console.log('ERROR: ', 'node is undefined')
if (!this instanceof DrawCircle) return new DrawCircle(opts)
this.opts = { // 默认参数
color: '#fff', // 字体颜色,border颜色
angle: 1, // 角度
lineWidth: 12, // border宽度
fontSize: '30px'
}
// 赋值
if (opts) {
for (var key in opts) {
opts[key] ? this.opts[key] = opts[key] : ''
}
}
// 查找canvas
if (typeof node === 'string') {
this.opts.node = document.getElementById(node)
} else {
this.opts.node = opts.node
}
this.getColor = function (angle) {
var colorArea = this.opts.colorArea || ['#17e439', '#fbc015', '#ff1919'] // 区域颜色 -- 对应从大到小
var colorArea2 = this.opts.colorArea2 || ['#d6f6db', '#faf1d5', '#fbd6d6'] // 背景颜色 -- 对应从大到小
var angleArea = this.opts.angleArea || [0.8, 0.6, 0] // 区域大小 -- 从大到小
for (var i = 0; i < angleArea.length; i ++) {
if (parseFloat(angle) >= angleArea[i]) {
this.opts.color = colorArea[i]
this.opts.background = colorArea2[i]
break
}
}
}
this.getColor(this.opts.angle)
// 初始化 画布
var canvasNode = this.opts.node
var cCenter = this.opts.cCenter = canvasNode.width / 2
var bBegin = Math.PI / 1
var bEnd = Math.PI * 2
var ctx = canvasNode.getContext('2d')
ctx.textAlign = 'center'
ctx.font = 'normal normal bold ' + this.opts.fontSize + ' Impact' // 定义字体加粗大小字体样式
ctx.fillStyle = this.opts.background
ctx.lineCap = 'round'
ctx.lineWidth = this.opts.lineWidth
ctx.beginPath()
ctx.strokeStyle = this.opts.background;
ctx.arc(cCenter, cCenter, (cCenter - this.opts.lineWidth), -bBegin, bEnd, false)
ctx.fill();//画实心圆
ctx.stroke()
//画实心小圆
ctx.beginPath();
ctx.arc(5, cCenter, 5, 0, 360, false)
ctx.fillStyle=this.opts.color;
ctx.fill();
ctx.closePath();
ctx.fillText((this.opts.angle * 100) + '%', cCenter, cCenter + this.opts.lineWidth)
var imd = ctx.getImageData(0, 0, 240, 240)
this.draw = function (current) { // 绘制
ctx.putImageData(imd, 0, 0)
ctx.beginPath()
ctx.strokeStyle = this.opts.color
ctx.arc(cCenter, cCenter, (cCenter - this.opts.lineWidth), -bBegin, (bEnd * current) - bBegin, false)
ctx.stroke()
};
var bit = 0
this.init = function (angle) { // 循环画 频率 0.015
var timer = setInterval(function () {
if (bit > angle) {
this.draw(this.opts.angle)
clearInterval(timer)
} else {
this.draw(bit)
bit += 0.015
}
}, 20);
}
this.init(this.opts.angle)
}
/**
* node: 传ID 或者指定的 节点 ---必传
* lineWidth:远的外圈宽度 --- 默认 12
* fontSize: 文字大小 默认 30px
* angle: 角度(百分比) --- 默认1 范围 0-1
* colorArea:范围区域的颜色 ---默认 ['#17e439', '#ffba00', '#ff0000']
* angleArea:范围区域的限定 ---默认 [1, 0.8, 0.6]
*/
var opts = {
node: 'circle',
angle: 0.8,
lineWidth: 6,
fontSize: '36px'
}
DrawCircle(opts)
复制代码
转载于:https://juejin.im/post/5b9b29a26fb9a05d00459bce