Chart js register new chart elements

211 views Asked by At

In Chart js version 3.9 i am trying to register new custom PointElement. I made my CustomeElement in the following way:

export default class CustomPointElement extends PointElement {
    draw(ctx: CanvasRenderingContext2D, area?: ChartArea) {
      // custom behavior
    }
}

And then i try to register it in the following way: Chart.register(CustomPointElement)

But i get the PointElement as the point controler. When checking this is because of this block of code in the register function:

    const proto = Object.getPrototypeOf(item);
    let parentScope;

    if (isIChartComponent(proto)) {
      // Make sure the parent is registered and note the scope where its defaults are.
      parentScope = this.register(proto);
    }

isIChartComponent is returning true and then the proto is registered. is there a way to extended the point element?

Doing the following works: Chart.registry.elements.items.point = PlacerPointElement; But getting a TS error: 'Property items does not exist on type TypedRegistry >'

1

There are 1 answers

0
kikon On

PointElement should already be registered if you registered registrables. One way I can think of for tricking the system to replace it, would be to change its static id before (first) registration, in a sequence like this (pure js):

import {Chart, PointElement, registerables} from "./chart.js";
PointElement.id = '_point'; // not used
class CustomPointElement extends PointElement {
    draw(ctx, area){
        //.....
    }
}
CustomPointElement.id = 'point'; 
// will register CustomPointElement under point

Chart.register(...registerables);
Chart.register(CustomPointElement);

This works (tested with chartjs 4.2, but should work with 3.9) because what matters is the key under which the Element is registered, and that is taken from the static id (and should be point).