Chart js doughnut box shadow

Viewed 6556

I need to add a shadow behind the doughnut, I tried with CSS like:

canvas {
  box-shadow: 12px 21px 24px 0px rgba(0, 0, 0, 0.21);
}

But that applies the shadow to the canvas box, not the doughnut.

How can I do this?

var myChart = new Chart(ctx, {
        type   : 'doughnut',
        data   : data,
  });
2 Answers

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

Related