【问题标题】:Chart.JS - Fill DonutChart.JS - 填充甜甜圈
【发布时间】:2016-11-07 19:57:16
【问题描述】:

我正在开发一个应用程序。这个应用程序使用 Chart.js 显示一些圆环图。我正在尝试用黄色填充甜甜圈“洞”。在甜甜圈洞内,我想放置一个图像。但是,我的尝试没有成功。目前,我有以下,可以在这个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);

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

【问题讨论】:

标签: javascript chart.js


【解决方案1】:

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 在圆环图中显示图像

【讨论】:

  • 一开始看起来不错,但当您将鼠标悬停在图表的弧线上时,背景颜色就会消失。
  • 更新了我的答案。我还添加了另一个问题的链接,您也可以参考。
猜你喜欢
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 2014-10-28
相关资源
最近更新 更多