我的 Angular 应用程序中的组件上有 3 个图表。
我需要创建文本标签插件以显示在图表上。每个图表都需要为其分配特定的插件。我进行了很多搜索,但找不到任何解决方案。 截至目前,我正在使用
Chart.register()
全局注册插件,这使得外观不理想,因为所有标签插件都会应用于所有图表。
有什么方法可以将特定插件应用于特定图表吗?
我正在使用 ng2-charts 并像使用 BaseChartDirective 一样定义我的图表。
@ViewChildren(BaseChartDirective) charts?: QueryList<BaseChartDirective>;
我正在创建这样的插件
function createLabelPlugin(text: string, xPosition: number, yPosition: number) {
return {
id: 'customLabelPlugin',
afterDraw(chart: any) {
const ctx = chart.ctx;
ctx.save();
ctx.font = 'bold 16px Arial';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Draw the text at the specified position
ctx.fillText(text, xPosition, yPosition);
ctx.restore();
}
};
}
ng2-charts
has 库有一个名为 @Input
的 plugins
参数,您可以在其中提供要为特定图表设置的插件。
export class BaseChartDirective<
TType extends ChartType = ChartType,
TData = DefaultDataPoint<TType>,
TLabel = unknown,
>
implements OnDestroy, OnChanges
{
...
@Input() public plugins: Plugin<TType>[] = [];
要使用它,只需添加如下插件即可。
export class LineComponent {
plugins = [createLabelPlugin('qwerty', 0, 0)];
<canvas baseChart [type]="chartType" [data]="data" [options]="options" [plugins]="plugins">
</canvas>
如果您正在处理数据标签,我推荐chartjs-plugin-datalabels,非常适合在图表上显示标签。