这是我在 Angular 8 和一些 ES6 技术中使用上述答案的答案。新的百分比来自可观察者。
HTML 文件包含一个 SVG,该 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'); // create canvas element
this.canvas2dContext = this.canvas.getContext('2d'); // get context
const gr = this.canvas2dContext.createLinearGradient(0, 0, 101, 0); // create a gradient
this.canvas.width = 101; // 101 pixels incl.
this.canvas.height = 1; // as the gradient
const colorStops = [
{stop: 0.0, color: 'lightgreen'},
{stop: 0.9, color: 'orange'},
{stop: 1.0, color: 'red'},
];
for (const cs of colorStops) // add color stops
{
gr.addColorStop(cs.stop, cs.color);
}
this.canvas2dContext.fillStyle = gr; // set as fill style
this.canvas2dContext.fillRect(0, 0, 101, 1); // draw a single line
}
// method to get color of gradient at % position [0, 100]
getColor(percentage: number) {
return this.canvas2dContext.getImageData(percentage , 0, 1, 1).data;
}
}