我需要在甜甜圈后面添加一个阴影,我尝试使用CSS,如:
canvas {
box-shadow: 12px 21px 24px 0px rgba(0, 0, 0, 0.21);
}
但这会将阴影应用于画布盒,而不是甜甜圈。
我该怎么做?
var myChart = new Chart(ctx, {
type : 'doughnut',
data : data,
});
答案 0 :(得分:3)
您可以执行以下操作:
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>
&#13;
答案 1 :(得分:0)
在测试了几种方法后,定义了一个新插件,该插件与 beforeDraw 通知挂钩,以自定义画布选项对我来说效果最好。
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;
},
};
并在配置中创建图表时指定它:
const chart = new Chart(ctx, {
options={...}
data={...}
plugins=[ShadowPlugin]
})
有关详细信息,请查看 https://www.chartjs.org/docs/latest/developers/plugins.html