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

如何创建带间隙的三分段SVG环形路径?

解决方法:用角度计算替代手动写坐标

不需要手动硬算路径坐标,用角度+三角函数是最精准且易维护的方法,既能保证三段圆弧组成完整的椭圆环(你代码里用的是长半轴30、短半轴25的椭圆),又能精准控制段间的间隙。

核心思路

  1. 先明确固定参数:

    • 圆心坐标 (cx, cy):选(50,50)适配你的100x100 viewBox更合理
    • 椭圆长半轴rx=30、短半轴ry=25(和原代码一致)
    • 间隙角度:比如每段之间留2°间隙,三段共3个间隙,总间隙6°
    • 单段圆弧角度:(360° - 总间隙角度) / 3 = (360-6)/3 = 118°
  2. 用三角函数计算圆弧起点/终点:
    椭圆上任意角度θ(弧度制)的坐标公式:

    x = cx + rx * Math.cos(θ)
    y = cy + ry * Math.sin(θ)
    

    注意:SVG坐标系Y轴向下,0°对应右侧点(如(80,50)),顺时针为角度增加方向。

直接写死坐标的SVG代码

补上原代码缺失的stroke属性(没这个路径看不到),以下是留2°间隙的完整实现:

<svg viewBox="0 0 100 100">
  <linearGradient id="gradient" x1="0" y1="0" x2="0" y2="100%">
    <stop offset="0%" stop-color="#56c4fb" />
    <stop offset="100%" stop-color="#0baeff" />
  </linearGradient>
  <!-- 第一段:0° → 118° -->
  <path d="M80,50 A30,25 0 0,1 50.52,74.75" fill="none" stroke="url(#gradient)" stroke-width="4" />
  <!-- 第二段:120° → 238°(跳过2°间隙) -->
  <path d="M49.48,74.75 A30,25 0 0,1 20.52,49.48" fill="none" stroke="url(#gradient)" stroke-width="4" />
  <!-- 第三段:240° → 358°(跳过2°间隙) -->
  <path d="M20.52,49.48 A30,25 0 0,1 79.48,50.52" fill="none" stroke="url(#gradient)" stroke-width="4" />
</svg>

灵活的JS动态生成版

要调整间隙大小或椭圆参数时,用JS计算更方便:

<svg viewBox="0 0 100 100" id="ring"></svg>
<script>
  const svg = document.getElementById('ring');
  const cx = 50, cy = 50;
  const rx = 30, ry = 25;
  const gapDeg = 2; // 单段间隙角度
  const segmentDeg = (360 - gapDeg*3)/3; // 单段圆弧角度
  const rad = Math.PI/180; // 角度转弧度系数

  for(let i=0; i<3; i++) {
    const startDeg = i*(segmentDeg + gapDeg);
    const endDeg = startDeg + segmentDeg;
    // 计算起点终点坐标
    const startX = cx + rx * Math.cos(startDeg*rad);
    const startY = cy + ry * Math.sin(startDeg*rad);
    const endX = cx + rx * Math.cos(endDeg*rad);
    const endY = cy + ry * Math.sin(endDeg*rad);
    // 创建path元素
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', `M${startX.toFixed(2)},${startY.toFixed(2)} A${rx},${ry} 0 0,1 ${endX.toFixed(2)},${endY.toFixed(2)}`);
    path.setAttribute('fill', 'none');
    path.setAttribute('stroke', 'url(#gradient)');
    path.setAttribute('stroke-width', '4');
    svg.appendChild(path);
  }
</script>

关键细节

  • 原代码问题:没设置stroke和stroke-width导致路径不可见;圆心位置选得不合理,无法组成闭环。
  • 间隙调整:只需修改gapDeg数值,就能改变段间间隙大小,不用手动改坐标。
  • SVG圆弧参数:A rx,ry x-axis-rotation large-arc-flag sweep-flag x,y,这里large-arc-flag=0、sweep-flag=1,保证是顺时针短弧。

内容的提问来源于stack exchange,提问作者sir-haver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:25:22