Chartjs-How do I add an image in the middle of Donut Chart?(Chart.js)

2👍

The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw the images directly on the canvas using CanvasRenderingContext2D.drawImage().

Please have a look at your amended code below.

new Chart('myChart', {
  type: 'doughnut',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var image = new Image();      
      image.src = 'https://i.stack.imgur.com/S7tJH.png';      
      imageSize = 40;
      ctx.drawImage(image, chart.chart.width / 2 - imageSize / 2, chart.chart.height / 2 - imageSize / 2, imageSize, imageSize);
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C'],
    datasets: [{
      data: [50, 25, 25],
      backgroundColor: ['#ffff00', '#ffffa4', '#ced5df'],
      hoverBackgroundColor: ['#ffff00', '#ffffa4', '#ced5df'],
      hoverBorderColor: "rgba(234, 236, 244, 1)",
    }],
  },
  options: {
    maintainAspectRatio: false,
    tooltips: {
      backgroundColor: "rgb(255,255,255)",
      bodyFontColor: "#858796",
      borderColor: '#dddfeb',
      borderWidth: 1,
      xPadding: 15,
      yPadding: 15,
      displayColors: false,
      caretPadding: 10,
    },
    legend: {
      display: false
    },
    cutoutPercentage: 80,
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>

1👍

Uminder’s answer was quite helpful. Adding to that to place image at the center Update below code

afterDraw: chart => {
  var ctx = chart.chart.ctx;
  ctx.save();
  var image = new Image();      
  image.src = 'https://i.stack.imgur.com/S7tJH.png';      
  imageSize = 40;
  const {top, left, width, height} = chart.chartArea;
  const x = left + width / 2 - imageSize / 2;
  const y = top + height / 2 - imageSize / 2;
  ctx.drawImage(image, x , y, imageSize, imageSize);
  ctx.restore();
}

Official Docs. I hope somebody will find it helpful.

0👍

https://dotnetfiddle.net/jJKo4I

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

credit to
How to add image inside the doughnut chart using chart.js?
and
https://www.c-sharpcorner.com/article/charts-in-asp-net-mvc-using-chart-js/
and
http://jsfiddle.net/jimrhoskins/Sv87G/

Leave a comment