JS Canvas生成带顶点圆圈的多边形问题求助
问题原因及修复方案
核心问题
- 路径未隔离:
draw()函数绘制圆圈时未调用ctx.beginPath(),导致圆圈路径与多边形路径合并,最终填充时会覆盖所有路径区域,破坏预期效果。 - 坐标计算错误:
draw()函数内的顶点坐标未乘以size,导致圆圈出现在画布中心附近,而非多边形顶点位置。 - 顶点重复绘制:原循环条件
i <= n会生成n+1个点(含与第一个顶点重合的点),造成冗余绘制。
修复后的代码
JavaScript 代码
function draw(x, y, ctx){ ctx.beginPath(); // 开启独立路径,隔离圆圈与多边形路径 ctx.arc(x, y, 4, 0, Math.PI * 2); ctx.fillStyle = "#283149"; ctx.fill(); } function createPolygon(n){ const canvas = document.getElementById("canvas"); const ctx = canvas.getContext('2d'); ctx.reset(); var size = 60, Xcenter = 80, Ycenter = 80; // 绘制多边形 ctx.beginPath(); const firstX = Xcenter + size * Math.cos(0); const firstY = Ycenter + size * Math.sin(0); ctx.moveTo(firstX, firstY); draw(firstX, firstY, ctx); // 绘制第一个顶点的圆圈 for (var i = 1; i < n; i++) { const x = Xcenter + size * Math.cos(i * 2 * Math.PI / n); const y = Ycenter + size * Math.sin(i * 2 * Math.PI / n); ctx.lineTo(x, y); draw(x, y, ctx); } ctx.closePath(); ctx.fillStyle = "#00818A"; ctx.fill(); }
HTML 代码
<button onclick="createPolygon(4)">Create 4</button> <canvas id="canvas" width="160" height="160"></canvas>
额外优化说明
- 给canvas添加宽高属性,避免默认拉伸导致图形变形。
- 循环条件改为
i < n,避免重复绘制重合顶点,减少冗余操作。 - 单独处理第一个顶点的绘制,确保所有顶点都带有圆圈。
内容的提问来源于stack exchange,提问作者The Myth
相关产品推荐
相关产品推荐

