Chartjs-Creating a Custom Point Element In Chart JS

0👍

Point elements are not among the elements advertised as
extendable in the docs,
neither are other types of elements (arc, bar, line).
There’s also no mechanism to choose the type (class) of
elements used by the chart.

Maybe I’m missing something, the extension class
is correct, but I’m curious where did you
get the registration format in your code from; it’s different
from registration of custom controllers or scales, which
is based on setting a static id to the class and
just calling Chart.register(CustomControllerClass).

If you really want to use custom points, you may do so
by replacing the standard PointElement class by
your class in the registry:

Chart.elements.PointElement = CustomPointElement;

jsFiddle.
This has the drawback that it wouldn’t be an alternative
to the standard PointElement to use for some datasets,
but the only one to be used for all datasets.

However, if custom drawing is all you want to do
there is a standard, sanctioned, way to do it in
chart.js: by setting
pointStyle
to an Image or a canvas element.
This, combined with the fact that pointStyle is scriptable
allows one to do useful custom drawing, having
access to the options that apply for that point.

const customPointCanvas = function(context, options){
    const cvs = document.createElement('canvas'),
        ctx = cvs.getContext('2d'),
        radius = options.pointRadius || 5;
    cvs.height = 2*radius;
    cvs.width = 2*radius;
    //star from https://stackoverflow.com/a/58043598/16466946
    const nSpikes = 5, x0 = cvs.width/2, y0 = cvs.height/2;
    ctx.beginPath();
    for(let i = 0; i < nSpikes*2; i++){
        const rotation = Math.PI/2,
            angle = (i/(nSpikes*2))*Math.PI*2+rotation,
            dist = radius/2*(i%2)+radius/2,
            x = x0+Math.cos(angle)*dist,
            y = y0+Math.sin(angle)*dist;
        if(i === 0) {
            ctx.moveTo(x, y);
        }
        else{
            ctx.lineTo(x, y);
        }
    }
    ctx.closePath();
    ctx.fillStyle = options.backgroundColor;
    ctx.strokeStyle = options.borderColor;
    ctx.fill();
    ctx.stroke();
    return cvs;
}


const ctx = document.getElementById('myChart');

// create a new line chart in chartJS
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderWidth: 1,
            pointRadius: 10,
            pointStyle: customPointCanvas
        }]
    },
})
<div style="height: 400px; width:98vw">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.0/chart.umd.js" integrity="sha512-CMF3tQtjOoOJoOKlsS7/2loJlkyctwzSoDK/S40iAB+MqWSaf50uObGQSk5Ny/gfRhRCjNLvoxuCvdnERU4WGg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Leave a comment