typescriptchart.jsradar-chart

get Coordinates of labels in radar chart js in order to replace labels with images


I have radar chart js and I want replace labels with images I tried to add images on dataset but I couldn't add them on labels [1, 2, 3, 4 ,5] radar chartjs

how can i put the images on the labels ? here's the code for the prev pic

` const images1 = ['https://i.sstatic.net/2RAv2.png', 'https://i.sstatic.net/Tq5DA.png', 'https://i.sstatic.net/3KRtW.png', 'https://i.sstatic.net/iLyVi.png', 'https://i.sstatic.net/Tq5DA.png'];

const radarChart = new Chart('chart', {
  type: 'radar',
  plugins: [{
    id: 'custom_labels',
    afterDraw: (chart) => {
      const ctx = chart.ctx;
      const datasetMeta = chart.getDatasetMeta(0);
  
      if (datasetMeta) {
        datasetMeta.data.forEach((element: any, index: number) => {
          const { x, y } = element.getCenterPoint();
          
          const img = new Image();
          img.src = images1[index];
  
          ctx.drawImage(img, x - img.width / 2, y - img.height / 2);
        });
      }
    }
  }],
  data: dataChart,
  options: {
    responsive: false,
    elements: {
      line: {
        borderWidth: 4,
      },
    },
    aspectRatio: 2,
    scales: {
      r: {
        pointLabels: {
          font: {
            size: 20,
          },
        },
      },
    },
    plugins: {
      legend: {
        labels: {
          font: {
            size: 20,
            weight: 'bold',
          },
        },
      },
    },
  },
});`

<canvas class="chart" width="500" height="500" id="chart"></canvas>

I tried to add images on dataset but I couldn't add them on labels [1, 2, 3, 4 ,5] I expected to add images on labels


Solution

  • You can get the x and y from the _pointLabelItems in the r scale:

    const options = {
      type: 'radar',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2],
            borderWidth: 1
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3],
            borderWidth: 1
          }
        ]
      },
      options: {},
      plugins: [{
        id: 'custom_labels',
        afterDraw: (chart) => {
          chart.scales.r._pointLabelItems.forEach((element, index) => {
            ctx.beginPath();
            ctx.rect(element.x, element.y, 20, 20);
            ctx.stroke();
          });
        }
    
      }]
    }
    
    const ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
    
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
    </body>