本教程演示了使用JavaScript和HTML5画布创建PIE和DONUT图表。
我们将介绍PIE和DONUT图表的基本原理,然后构建JavaScript和HTML以渲染它们。
了解派和甜甜圈图
>饼图在视觉上表示数值数据是圆圈内的尺寸切片。 每个切片对应于数据类别。甜甜圈图是一个变化。这是一个饼图,中间有一个孔,类似于甜甜圈。
入门:设置项目>
index.html
)。
script.js
index.html
<canvas id="myCanvas"></canvas>
在创建图表之前,让我们覆盖基础知识:绘图线,弧线(圆圈的部分)和使用画布填充的形状。 我们将为每个定义JavaScript函数:
function drawLine(ctx, x1, y1, x2, y2, color) { ctx.beginPath(); ctx.strokeStyle = color; ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } function drawArc(ctx, x, y, radius, startAngle, endAngle, color) { ctx.beginPath(); ctx.strokeStyle = color; ctx.arc(x, y, radius, startAngle, endAngle); ctx.stroke(); } function drawPieSlice(ctx, centerX, centerY, radius, startAngle, endAngle, fillColor, strokeColor) { ctx.save(); ctx.fillStyle = fillColor; ctx.strokeStyle = strokeColor; ctx.beginPath(); ctx.moveTo(centerX, centerY); ctx.arc(centerX, centerY, radius, startAngle, endAngle); ctx.closePath(); ctx.fill(); ctx.stroke(); ctx.restore(); }
script.js
>
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); drawLine(ctx, 200, 200, 300, 300, "#000"); drawArc(ctx, 250, 250, 150, 0, Math.PI/3, "#000"); drawPieSlice(ctx, 250, 250, 150, Math.PI/2, Math.PI/2 + Math.PI/3, "#F00", "#000");
>绘制图表的完整JavaScript代码(包括用于更好组织和处理选项的类结构)非常广泛,并且超出了简洁响应的范围。 但是,核心逻辑涉及通过进行迭代,根据每个切片的比例计算每个切片的角度,并使用
>
以上是如何使用JavaScript和HTML5画布绘制图表的详细内容。更多信息请关注PHP中文网其他相关文章!