绘制饼状图
设想你刚刚从 EconomiCorp 获得了一份工作,并且你的第一个任务是画出一个描述其用户满意度调查结果的饼状图。results绑定包含了一个表示调查结果的对象的数组。
const results = [{name: "Satisfied", count: 1043, color: "lightblue"},{name: "Neutral", count: 563, color: "lightgreen"},{name: "Unsatisfied", count: 510, color: "pink"},{name: "No comment", count: 175, color: "silver"}];
要想画出一个饼状图,我们需要画出很多个饼状图的切片,每个切片由一个圆弧与两条到圆心的线段组成。我们可以通过把一个整圆(2π)分割成以调查结果数量为单位的若干份,然后乘以做出相应选择的用户的个数来计算每个圆弧的角度。
<canvas width="200" height="200"></canvas><script>let cx = document.querySelector("canvas").getContext("2d");let total = results.reduce((sum, {count}) => sum + count, 0);// Start at the toplet currentAngle = -0.5 * Math.PI;for (let result of results) {let sliceAngle = (result.count / total) * 2 * Math.PI;cx.beginPath();// center=100,100, radius=100// from current angle, clockwise by slice's anglecx.arc(100, 100, 100,currentAngle, currentAngle + sliceAngle);currentAngle += sliceAngle;cx.lineTo(100, 100);cx.fillStyle = result.color;cx.fill();}</script>
但表格并没有告诉我们切片代表的含义,它毫无用处。因此我们需要将文字画在画布上。
