矩形画布中的圆形饼图

时间:2017-06-21 16:26:11

标签: chart.js chart.js2

可以在右边找到带有图例的漂亮饼图吗?

当我设置矩形画布时,会发生坏事,具体取决于HTML属性,CSS属性和Chart.js的responsive设置的确切组合:

  • 画布变成方形,馅饼本身看起来很小
  • 图形拉伸以适合画布,饼图变为椭圆
  • 无论如何我的自定义尺寸都会被忽略,之前发生的一些事情会发生

E.g:



new Chart("foo", {
    type: "pie",
    data: {
        labels: [
            "Lorem ipsum dolor sit",
            "Morbi nec lacus",
            "Others"
        ],
        datasets: [
            {
                data: ["134", "74", "13"]
            }
        ]
    },
    options: {
        responsive: true,
        legend: {
            position: "right",
            labels: {
                usePointStyle: true
            }
        }
    }
});

figure {
    position: relative;
    width: 300px;
    height: 150px;
}
canvas {
    border: 1px solid salmon;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<figure><canvas id="foo"></canvas></figure>
&#13;
&#13;
&#13;

饼图只是设计成方形吗?

1 个答案:

答案 0 :(得分:1)

要完成此操作,您需要设置canvas元素宽度和高度,使用它本机属性(不是style / css)< / em>的

<canvas id="foo" width="300" height="150"></canvas>

注意: 此宽度和高度值必须是您为画布包装器元素设置的值的一半(<figure>)< / em>的

<强>ᴅᴇᴍᴏ

new Chart(foo, {
   type: "pie",
   data: {
      labels: [
         "Lorem ipsum dolor sit",
         "Morbi nec lacus",
         "Others"
      ],
      datasets: [{
         data: ["134", "74", "13"]
      }]
   },
   options: {
      responsive: true,
      legend: {
         position: "right",
         labels: {
            usePointStyle: true
         }
      }
   }
});
figure {
    position: relative;
    width: 300px;
    height: 150px;
}
canvas {
   border: 1px solid salmon;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<figure>
   <canvas id="foo" width="150" height="75"></canvas>
</figure>

另一种方法

没有画布包装并将responsive属性设置为false

new Chart(foo, {
   type: "pie",
   data: {
      labels: [
         "Lorem ipsum dolor sit",
         "Morbi nec lacus",
         "Others"
      ],
      datasets: [{
         data: ["134", "74", "13"]
      }]
   },
   options: {
      responsive: false,
      legend: {
         position: "right",
         labels: {
            usePointStyle: true
         }
      }
   }
});
canvas {
   border: 1px solid salmon;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="foo" width="300" height="150"></canvas>