如何在chart.js饼图段中添加叠加颜色?

时间:2016-05-06 11:53:20

标签: javascript php charts chart.js

我正在使用Chart.js在我的网页上绘制图表。

我已成功通过以下代码绘制饼图:

var dataPiChart = [
            {
                value: 350,
                color:"#F7464A",
                highlight: "#FF5A5E",
                label: "PHP"
            },
            {
                value: 100,
                color: "#46BFBD",
                highlight: "#5AD3D1",
                label: "JavaScript"
            },
            {
                value: 500,
                color: "#FDB45C",
                highlight: "#FFC870",
                label: "HTML"
            }
        ];

new Chart(document.getElementById('canvas').getContext("2d")).Pie(dataPiChart, {
                legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
            });

注意:此处canvas是我的画布ID。它按照我想要的方式工作正常。现在我有一个每个数据集的值,它是ex:PHP - 20%, JavaScript- 30%, HTML - 20%的%完成值。现在我想制作20%的深色PHP段和80%的淡化色不完整的PHP段。一些如何区分完成多少%。

1 个答案:

答案 0 :(得分:0)

创建一个新的画布对象并将其放置在实际图表下。此新图表具有拆分数据值。确保原始图表中分割的数据点具有透明背景,以便显示底层分割。

预览

enter image description here

<强> HTML

<div class="splitContainer">
  <canvas id="canvas" height="300" width="800"></canvas>
  <canvas class="canvasSplit" id="canvas2" height="300" width="800"></canvas>
</div>

<强> CSS

.splitContainer {
  position: relative;
}

.canvasSplit {
  z-index: -1;
  position: absolute;
  top: 0;
  left: 0;
}

<强>脚本

var dataPiChart2 = [
  {
    value: 200,
    color:"rgba(247, 70, 74, 0.6)",
    label: "PHP1"
  },
  {
    value: 150,
    color:"rgba(247, 70, 74, 0.2)",
    label: "PHP2"
  },
  // values that are not split remain as is
  {
    value: 100,
    color: "#46BFBD",
    label: "JavaScript"
  },
  {
    value: 500,
    color: "#FDB45C",
    label: "HTML"
  }
];

new Chart(document.getElementById('canvas2').getContext("2d")).Pie(dataPiChart2, {
  segmentShowStroke: false
});

var dataPiChart = [
  {
    value: 350,
    // transparent show the split shows through
    color:"rgba(247, 70, 74, 0.2)",
    highlight: "rgba(247, 70, 74, 0.7)",
    label: "PHP"
  },

小提琴 - http://jsfiddle.net/ww8qpdvw/