矩形画布中的圆形饼图

  • 本文关键字:布中 chart.js chart.js2
  • 更新时间 :
  • 英文 :

有可能

得到一个带有图例的好看的饼图吗?

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

  • 画布变成正方形,馅饼本身看起来很小
  • 图形拉伸以适合画布,饼图变成椭圆
  • 无论如何,我的自定义大小都被忽略了,并且发生了前两件事中的一些

例如:

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>

饼图只设计为正方形吗?

为此,您需要使用画布元素本机属性(不是样式/css(设置画布元素宽度和高度。

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

注: 此宽度和高度值必须是您为 Canvas 包装器元素 ( <figure> ( 设置的值的一半

ᴅᴇᴍᴏ

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>

相关内容

  • 没有找到相关文章

最新更新