一、示例图
二、实现步骤
html:
<canvas #canvasDom width="{{width}}" height="{{height}}" #canvas>
您的浏览器不支持画布
</canvas>
1.设置背景圆环
// 背景圆环
drawArc() {
// 设置宽高
this.context = this.canvasDom.nativeElement.getContext('2d');
const context = this.context;
this.canvasDom.nativeElement.width = this.width;
this.canvasDom.nativeElement.height = this.height;
// 外层圆环
context.beginPath();
context.strokeStyle = '#ebebeb'; // 颜色
context.arc(100, 100, 80, (Math.PI / 180) * 270, (Math.PI / 180) * -90, false);
context.lineWidth = 20;
context.closePath();
context.stroke();
// 设置着色圆环
this.frameArc();
}
2.设置内层圆环-运动效果
// 动态圆环
frameArc() {
const speed = 20; // 速度
let stepDeg = 0; // 初始值
let timer = setInterval(() => {
stepDeg += 1; // 以1为间距
// 若当前数值已大于传入数值,则清除定时器
if (stepDeg >= this.rate) {
clearInterval(timer);
}
// 内层圆环
const context = this.context;
context.beginPath();
// 设置渐变色
const gradient = context.createLinearGradient(0, 20, 0, 120);
gradient.addColorStop('0', '#ffaa03');
gradient.addColorStop('1.0', '#ff4514');
context.strokeStyle = gradient;
context.lineCap = 'round'; // 使其形状为圆弧
context.arc(100, 100, 80, (Math.PI / 180) * 270, (Math.PI / 180) * (270 + (stepDeg / 100 * 360)), false);
context.lineWidth = 20; // 圆环的宽度
context.stroke();
context.closePath();
}, speed);
}
3.设置图表上文字
drawText() {
const cans = this.canvasDom.nativeElement.getContext('2d');
cans.font = 'bold 44px Arial'; // 字体
cans.fillStyle = '#676767'; // 字体颜色
cans.textAlign = 'center'; // 使文字居中
cans.fillText(this.rate + '%', this.width / 2, this.height / 2 + 15);
}