[Chartjs]-Chartjs 3.5.0 – Radar Chart – Converting the labels to images

1πŸ‘

βœ…

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>

Leave a comment