Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
Getting the closest intersection to a click on Chart.js

I'm using chart.js to make a radar chart that the user should be able to interact on their own. The idea is that if the user clicks on the red spot, the app should know whether the green spot is the closest intersection of ticks and angle lines, so that it can change the dataset value at index 1 (corresponding to B) from 2 (corresponding to mid-low) to 4 (mid-high).

Chart

And it's set up like this:

    const chartData = {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
        fill: true,
        backgroundColor: 'rgba(6,211,248,0.5)',
        borderColor: 'rgb(6,211,248)',
        data: mockData.presetValues.a,
    }]
};
const chartConfig = {
    type: 'radar',
    data: chartData,
    options: {
        elements: {
            line: {
                borderWidth: 3
            },

        },
        scales: {
            r: {
                min: 0,
                max: 5,
                ticks: {
                    stepSize: 1,
                    callback: function (value) {
                        return ['none', 'low', 'mid-low', 'mid', 'mid-high', 'high'][value]
                    }
                },
                grid: {
                    circular: true,
                    lineWidth: 5
                },
                angleLines: {
                    color: 'black',

                }

            }
        },
        plugins: {
            legend: {
                display: false
            }
        },
        events: ['click']
    }
};
const actionChart = new Chart(
    canvas,
    chartConfig
);

Then I have a listener set up for it like so:

canvas.addEventListener('click', handleChartClick)

And finally I have a handler like this, which is where my problem is:

    function handleChartClick(ev) {
    let clickPosition = Chart.helpers.getRelativePosition(ev, actionChart);
    console.log(clickPosition);
    //Find closest tick to click and change values in dataset before refresh
}

After hours of scouring the documentation and this site, I can not find a way of correlating the position of the click that I receive from the getRelativePosition method with the position of the intersections between the angle lines and the ticks. Once I have those two pieces of information I can modify the dataset and refresh, but I'd greatly appreciate if anyone could help me figure out how to get the closest intersection to the click.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could use onClick option of chart in order to catch click event (instead of adding a listener to the canvas). In this way the passed event is already normalized.

The callback could be something like that, in order to have the closest tick:

options: {
  ...
  onClick(event, elements, chart) {
    const scale = chart.scales.r;
    const posY = Math.abs(scale.getDecimalForPixel(event.y) - 0.5);
    const posX = Math.abs(scale.getDecimalForPixel(event.x) - 0.5);
    const scalePosition = Math.max(posY, posX);
    const value = Math.round(scalePosition * 10);
    console.log(['none', 'low', 'mid-low', 'mid', 'mid-high', 'high'][value]); // shows value
  },
  ...
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda