如何将笔划添加到Chart.js饼图中

How can I add stroke to Chart.js Pie Charts?

本文关键字:js Chart 添加      更新时间:2024-06-22

我希望饼图中的每个部分都有自己的笔划颜色。现在,它似乎只做一个全局笔划——我能在每个饼段上得到一个笔划吗?我尝试了以下几种,但没有成功:

Chart.defaults.global.segmentShowStroke = true;
var ctx = document.getElementById("myChart").getContext("2d");
var data = [{
  value: 300,
  color: "#F7464A",
  highlight: "#FF5A5E",
  stroke: "#FF0000", // Doesn't work
  label: "Red"
}, {
  value: 50,
  color: "#46BFBD",
  highlight: "#5AD3D1",
  strokeColor: "#00FF00", // Doesn't work
  label: "Green"
}, {
  value: 100,
  color: "#FDB45C",
  highlight: "#FFC870",
  segmentStrokeColor: "#88FF00", // Doesn't work
  label: "Yellow"
}];
/**
 * Whether or not segmentStrokeColor is enabled,
 * the previous stroke options do not work.
 */
var options = {
  segmentStrokeColor: "black" // Works. Defaults to "white" if removed
};
var myPieChart = new Chart(ctx).Pie(data, options);
canvas {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
<canvas id="myChart" width="150" height="150"></canvas>

请注意,即使从options变量中删除了segmentStrokeColor,之前为每个饼图段的笔划着色的尝试也不会起作用。

与饼图和条形图不同,饼图不支持每个分段的strokeColor,它只使用全局的。

实现所需效果的唯一方法是扩展饼图,复制addData方法,并使用segment.strokeColor而不是this.options.segmentStrokeColor

Chart.types.Pie.extend({
    name: 'SegmentStrokeColorPie',
    addData : function(segment, atIndex, silent){
      ...
      [Copy all the addData method here, only change the line below]
      ...
          strokeColor : segment.strokeColor,
      ...
      ...
    }
});
var data = [
    {
        value: 300,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Red",
        strokeColor: "#FF0000"
    },
    {
        value: 50,
        color: "#46BFBD",
        highlight: "#5AD3D1",
        label: "Green",
        strokeColor: "#00FF00"
    }
];
new Chart(ctx).SegmentStrokeColorPie(data);