October 24, 2024
Chicago 12, Melborne City, USA
javascript

Applying custom plugins to specific charts in Chart.js (not globally)


I have 3 charts on a component in my angular app.

I need to create text label plugins to show on the chart. Each chart needs to have specific plugin assigned to it. I have searched a lot and could not find any solution.
As of now i am registering the plugins globally with Chart.register() which is making the appearance undesirable because all of the label plugins gets applied to all of the charts.

is there any way to apply specific plugins to specific charts?

I am using ng2-charts and defining my charts like with BaseChartDirective.

@ViewChildren(BaseChartDirective) charts?: QueryList<BaseChartDirective>;

I am creating plugins like this

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();
    }
  };
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video