这是我的答案,使用Angular 8和一些ES6技术。新的百分比通过一个observable传入。
HTML文件包含一个SVG,其中有两个与类相关联的属性。类似于这样的东西:
<svg>
<circle [attr.stroke]='strokeColor' [attr.fill]='fillColor'>
</svg>
应用程序的TypeScript文件:
import {Component, Input, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
@Component({
selector: 'app-real-time-indicator',
templateUrl: './real-time-indicator.component.html',
styleUrls: ['./real-time-indicator.component.css']
})
export class RealTimeIndicatorComponent implements OnInit {
@Input() percentagePassed$: Observable<number>;
@Input() minutesRemaining$: Observable<number>;
public currentPercentage: number;
public minutesRemaining: number;
private canvas2dContext: any;
private canvas: any;
public fillColor: string;
public strokeColor: string;
constructor() {
}
ngOnInit(): void {
this.percentagePassed$.subscribe((newValue) => {
this.currentPercentage = 100 - newValue;
let [r, g, b] = this.getColor( newValue);
this.fillColor = `rgb(${r},${g},${b})`;
[r, g, b] = this.getColor( 100 - newValue);
this.strokeColor = `rgb(${r},${g},${b})`;
});
this.canvas = document.createElement('canvas');
this.canvas2dContext = this.canvas.getContext('2d');
const gr = this.canvas2dContext.createLinearGradient(0, 0, 101, 0);
this.canvas.width = 101;
this.canvas.height = 1;
const colorStops = [
{stop: 0.0, color: 'lightgreen'},
{stop: 0.9, color: 'orange'},
{stop: 1.0, color: 'red'},
];
for (const cs of colorStops)
{
gr.addColorStop(cs.stop, cs.color);
}
this.canvas2dContext.fillStyle = gr;
this.canvas2dContext.fillRect(0, 0, 101, 1);
}
getColor(percentage: number) {
return this.canvas2dContext.getImageData(percentage , 0, 1, 1).data;
}
}