You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS Canvas生成带顶点圆圈的多边形问题求助

问题原因及修复方案

核心问题

  1. 路径未隔离:draw()函数绘制圆圈时未调用ctx.beginPath(),导致圆圈路径与多边形路径合并,最终填充时会覆盖所有路径区域,破坏预期效果。
  2. 坐标计算错误:draw()函数内的顶点坐标未乘以size,导致圆圈出现在画布中心附近,而非多边形顶点位置。
  3. 顶点重复绘制:原循环条件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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:35:22