Chart.JS - 填充甜甜圈

时间:2016-11-07 19:57:16

标签: javascript chart.js

我正在开发一款应用。这个应用程序使用Chart.js显示一些圆环图。我试图填满甜甜圈" hole"黄色。在甜甜圈洞内,我想要放置一个图像。但是,我的尝试没有成功。目前,我有以下内容,可在此Fiddle中看到。

var data = [{
    value: 30,
    color: "#F7464A"
}, {
    value: 50,
    color: "#E2EAE9"
}, {
    value: 100,
    color: "#D4CCC5"
}, {
    value: 40,
    color: "#949FB1"
}, {
    value: 120,
    color: "#4D5360"
}

]

var options = {
    animation: false,
    backgroundColor: [
        'yellow'
    ]
};

//Get the context of the canvas element we want to select
var c = $('#myChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("myChart").getContext("2d");
/*************************************************************************/
myNewChart = new Chart(ct).Doughnut(data, options);

如何自定义甜甜圈填充?谢谢!

1 个答案:

答案 0 :(得分:0)

options之后添加此内容:

Chart.types.Doughnut.extend({
    name: "DoughnutAlt",
    draw: function () {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);

          //find the center point
          var x = this.chart.canvas.clientWidth / 2;
          var y = this.chart.canvas.clientHeight / 2;

          //render the text
          this.chart.ctx.beginPath();
          this.chart.ctx.arc(x,y,100,0,2*Math.PI);
          this.chart.ctx.fillStyle = '#ffff00';
          this.chart.ctx.fill();
    }
});

myNewChart = new Chart(ct).Doughnut(data, options);更改为myNewChart = new Chart(ct).DoughnutAlt(data, options);

更新了fiddle

请参阅此答案:canvas fill text vanishes when hovering over chartjs pie chart

<强>更新

添加背景图片:

var img = new Image();
img.src = 'path_to_image_source';

this.chart.ctx.drawImage(img,135,130);

更新了显示圆圈图中的图片的jsfiddle

相关问题