矩形圆形饼图 canvas

Round pie chart in rectangular canvas

能不能做出一个好看的带图例的饼图?

当我设置矩形时 canvas 会发生不好的事情,具体取决于 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>

饼图只能设计成正方形吗?

为此,您需要设置canvas元素宽度和高度,使用它本机属性 (不是 style/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>

另一种方法

没有 canvas 包装器并将 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>