export function initCanvas(obj) {
this.x0 = obj.x0 // 圆心坐标
this.y0 = obj.y0 // 圆心坐标
this.r1 = obj.r1 // 外圆半径
this.endAng = obj.endAng // 终点角度
this.gradient = obj.color //颜色
this.degActive = 0
this.canvas = document.getElementById(obj.el);
var width = this.canvas.width
var height = this.canvas.height
this.canvas.style.height = height + "px";
this.canvas.style.width = width + "px";
this.canvas.height = height * 4;
this.canvas.width = width * 4;
this.ctx = this.canvas.getContext("2d");
this.ctx.scale(4, 4)
this.timer = setInterval(() => {
if (this.degActive > this.endAng / 100 * 360) { //停止定时器
clearInterval(this.timer);
} else {
this.ctx.clearRect(0, 0, width, height);//清除画布
let txt = (parseInt(this.degActive * 100 / 360) + "%");//获取百分比
this.ctx.font = 20 + "px SimHei";
let w = this.ctx.measureText(txt).width;//获取文本宽度
let h = 12 ;
this.ctx.fillStyle = "#fff";
this.ctx.fillText(txt,this.x0-w/2, this.y0+h/2);
this.degActive++;
if (this.endAng <= 50) {
this.gradient = this.ctx.createLinearGradient(0, 0, 0, 120);
this.gradient.addColorStop(0, obj.color[0]);
this.gradient.addColorStop(1, obj.color[1]);
} else if (this.endAng >= 50 && this.endAng < 100) {
this.gradient = this.ctx.createLinearGradient(-120, 0, 0, 120);
this.gradient.addColorStop(0, obj.color[0]);
this.gradient.addColorStop(1, obj.color[1]);
} else if (this.endAng >= 100) {
this.gradient = this.ctx.createLinearGradient(88, 168, 88, 0);
this.gradient.addColorStop(0, obj.color[0]);
this.gradient.addColorStop(1, obj.color[1]);
}
drawColorArc(obj, this.degActive, this.gradient, this.ctx)
}
},this.timer)
}
function drawColorArc(obj, degActive, gradient, ctx) {
ctx.beginPath(); //开始绘制底圆
ctx.lineWidth = obj.lineWidth;
ctx.arc(obj.x0, obj.y0, obj.r1, 0, Math.PI * 2, false);
ctx.strokeStyle = "#fff";
ctx.stroke();
ctx.beginPath(); //开始绘制动态圆
ctx.arc(obj.x0, obj.y0, obj.r1, Math.PI / 2, (Math.PI / 180) * degActive + Math.PI / 2, false);
ctx.lineWidth = obj.lineWidth;
ctx.strokeStyle = gradient;
ctx.lineCap = "round"
ctx.stroke();
}
new initCanvas({ el: "cavans_man", color: ["#73fbe9", "#fff"], x0: 30, y0: 30, endAng: 50, r1: 25, lineWidth: 10 });