[Chartjs]-How to style a pie chart in chart js? I want to change the border color, border width and give them shadow

2👍

First at all, you should upgrade to the most stable version of Chart.js, which currently is v2.9.4.

The dataset accepts number of properties, that can be defined for styling the border. Its color and width are controlled through the following ones.

  • borderColor arc border color
  • borderWidth arc border width (in pixels).

In order to see a shadow, you can use the Plugin Core API. The API offers a range of hooks that may be used for performing custom code. In the beforeDraw for example, you can draw a circle with shadow through CanvasRenderingContext2D.arc().

Please take a look at your amended code below and see how it works.

new Chart('canvas', {
  type: 'pie',
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      ctx.beginPath();
      ctx.fillStyle = 'white';
      ctx.shadowColor = 'black';
      ctx.shadowBlur = 20;
      ctx.shadowOffsetX = -10;
      ctx.shadowOffsetY = 0;
      const x = chart.chart.width / 2;
      const y = chart.chart.height / 2 + 15;
      ctx.arc(x, y, 95, 0, Math.PI*2, false);
      ctx.fill();
      ctx.restore();
    }
  }],
  data: {
    labels: ['Dr. John', 'Alex', 'Other'],
    datasets: [{
      data: [923864, 720988, 179539],
      backgroundColor: ['#58508d', '#3292b0', 'orange'],
      hoverBackgroundColor: ['#003f5c', '#6fefff', 'darkblue'],
      borderWidth: 0
    }],
  },
  options: {
    responsive: false,
    layout: {
      padding: {
        top: 15,
        bottom: 20
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="canvas" height="260"></canvas>

Leave a comment