[Chartjs]-Chart js doughnut box shadow

4👍

You can do the following:

  var draw = Chart.controllers.doughnut.prototype.draw;
    Chart.controllers.doughnut = Chart.controllers.doughnut.extend({
    draw: function() {
        draw.apply(this, arguments);
        let ctx = this.chart.chart.ctx;
        let _fill = ctx.fill;
        ctx.fill = function() {
            ctx.save();
            ctx.shadowColor = 'blue';
            ctx.shadowBlur = 25;
            ctx.shadowOffsetX = 2;
            ctx.shadowOffsetY = 2;
            _fill.apply(this, arguments)
            ctx.restore();
        }
    }
    });
  
  
  var ctx = document.getElementById("doughnut-chart");
  var myDoughnutChart =new Chart(ctx,{
    type: 'doughnut',
    data: {
      labels: ["apple", "banana", "orange"],
      datasets: [
        {
          label: "Favourite",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f"],
          data: [1,2,3]
        }
      ]
    },
    options: {
      title: {
        display: false
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<div>
<canvas id="doughnut-chart" width="600" height="300" style="background-color:#fff"></canvas></div>

3👍

After testing out several approaches, defining a new plugin which hooks into the beforeDraw notice to customize the canvas’ options worked best for me.

const ShadowPlugin = {
  beforeDraw: (chart, args, options) => {
    const { ctx } = chart;
    ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
    ctx.shadowBlur = 10;
    ctx.shadowOffsetX = 5;
    ctx.shadowOffsetY = 5;
  },
};

And specify it when creating your Chart in the config as such:

const chart = new Chart(ctx, {
    options={...}
    data={...}
    plugins=[ShadowPlugin]
})

For more info, check out https://www.chartjs.org/docs/latest/developers/plugins.html

Leave a comment