Chartjs饼图,径向位移(偏移)

时间:2017-03-10 17:17:24

标签: javascript chart.js2

Chartjs 2是否支持饼段的径向位移(偏移)?

enter image description here

1 个答案:

答案 0 :(得分:2)

Chart.js本身没有选择像这样削减一块。但你总是define your own chart type

这里我将pie图表子类化为cutOutPie类型。图表类配置"饼图"使用updateElement函数,所以我覆盖它并移动元素'位置。详细信息可以在reading the source找到。



Chart.defaults.cutOutPie = Chart.helpers.clone(Chart.defaults.pie);

Chart.controllers.cutOutPie = Chart.controllers.pie.extend({
    updateElement: function(arc, index, reset) {
        Chart.controllers.pie.prototype.updateElement.call(this, arc, index, reset);
        var displacement = this.getDataset().displacements[index]||0;
        var model = arc._model;
        var angle = model.startAngle + model.circumference/2;
        model.x += Math.cos(angle) * displacement;
        model.y += Math.sin(angle) * displacement;
    }
});

new Chart('chart', {
    type: 'cutOutPie',
    data: {
        labels: ['a', 'b', 'c', 'd', 'e', 'f'],
        datasets: [{
            data: [1, 7, 2, 8, 3, 9],
            backgroundColor: ['red', 'orange', 'green', 'gold', 'pink', 'blue'],
            displacements: [0, 0, 40, 0, 0, 16],
        }],
    },
});

<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" width="400" height="300"></canvas>
&#13;
&#13;
&#13;