Chartjs-How to get radar chart coordinates using getValueForDistanceFromCenter with Chart.js?

0đź‘Ť

The radialLinear scale (in version 2.9.4 that I have seen your are using version 2) there is the method getValueForDistanceFromCenter(value) to get the distance from center but there is another method getPointPositionForValue(index, value) which can provide you the point at a specif index of your data.

To use them and to draw what you want on chart using those points, you need to implement a plugin.
In the below snippet, I’m drawing a rect between the points at a specific value.

const ctx = document.getElementById("myChart");
const data = {
  labels: ["Ball Skills", "Shooting", "Physical"],
  datasets: [{
    label: [`ikke`, `jij`],
    backgroundColor: "rgba(38,120,255,0.2)",
    borderColor: "rgba(38,120,255, 1)",
    data: [50, 50, 50]
  }]
};

const options = {
  responsive: true,
  tooltips: false,
  title: {
    text: 'Basic example',
    display: true,
    position: `bottom`,
  },
  scale: {
    angleLines: {
      display: true
    },
    ticks: {
      suggestedMin: 0,
      suggestedMax: 100,
      stepSize: 25, 
      maxTicksLimit: 11,
      display: false, 
    }
  },
  legend: {
    labels: {
      padding: 10,
      fontSize: 14,
      lineHeight: 30,
    },
  },
};

const plugin = {
  id: 'getDistance',
  afterDraw(chart) {
    const c = chart.ctx;
    const rScale = chart.scale;
    c.save();
    chart.data.datasets[0].data.forEach(function(item, index) {
      const point = rScale.getPointPositionForValue(0.5 + index, 50);
      c.beginPath();
      c.fillStyle = 'red';
      c.fillRect(point.x - 5, point.y - 5, 10, 10);
      c.fill();
    });
    c.restore();
  }
};

const myChart = new Chart(ctx, {
  type: 'radar',
  plugins: [plugin],
  data: data,
  options: options
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment