Franky
Franky

Reputation: 35

Chartjs 3.5.0 - Radar Chart - Converting the labels to images

I am trying to replace my labels for the radar chart with images, I had a look at How to add an images as labels to Canvas Charts using chart.js but it wasn't helpful, I have managed to get the chart from get canvas

const callback = [
    {
      id: "custom",
      afterDraw: chart => {
      var ctx = chart.canvas.getContext("2d");
      console.log(chart) // logs the chart object
      var xAxis = chart.scales['r'];}
    },
];

Chartjs 3.5.0 - Radar Chart - Converting the labels to images. I am using this https://github.com/reactchartjs/react-chartjs-2

Upvotes: 3

Views: 1580

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31331

Here is an example I once made a time back, if you only want an image you can take out the part that draws the values of the labels on the chart in the function:

const image = new Image();
image.src = "http://www.lunapic.com/editor/premade/transparent.gif";

var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {
  type: "radar",
  data: {
    labels: [
      ['', ''],
      ['', ''],
      ['', '']
    ],
    datasets: [{
      label: "material font",
      backgroundColor: "rgb(255, 99, 132, 0.5)",
      borderColor: "rgb(255, 99, 132)",
      borderWidth: 1,
      data: [10, 20, 30],
    }, ]
  },
  options: {},
  plugins: [{
    id: 'custom_labels',
    afterDraw: (chart, args) => {
      if (image.complete) {
        const scale = chart.scales.r;
        drawTextAtIndex(scale, 0, 'headset', 'test0', 10);
        drawTextAtIndex(scale, 1, '3d_rotation', 'test1', 20);
        drawTextAtIndex(scale, 2, 'done', 'test2', 30);
      } else {
        image.onload = () => chart.draw();
      }
    }
  }]
});

function drawTextAtIndex(scale, index, icon, text) {
  const offset = 36;
  const r = scale.drawingArea + offset;
  const angle = scale.getIndexAngle(index) - Math.PI / 2;
  const x = scale.xCenter + Math.cos(angle) * r;
  const y = scale.yCenter + Math.sin(angle) * r;
  const ctx = scale.ctx;
  ctx.save();
  ctx.translate(x, y);
  //ctx.rotate(angle + Math.PI / 2);
  ctx.textAlign = 'center';

  ctx.fillStyle = 'blue';
  ctx.font = '20px material-icons'
  ctx.drawImage(image, -15, -2, 30, 30);

  ctx.font = "12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
  ctx.fillStyle = 'black';
  ctx.fillText(text, 0, -5);
  ctx.restore();
}
<div class="chart">
  <canvas id="chart"></canvas>
</div>
<script src="https://www.chartjs.org/dist/master/chart.js"></script>

Upvotes: 1

Related Questions