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

如何获取SVG圆形描边的所有(x,y)坐标点?用于SVG太阳系动画

获取SVG圆形描边上的坐标点方法

一、数学公式直接计算(推荐)

对于太阳系动画这种场景,不需要获取所有点,直接用三角函数推导坐标更高效:

  • 假设大圆轨道的圆心为(cx, cy),半径为r,目标点的角度为θ(弧度制),坐标公式为:
    • x = cx + r * cos(θ)
    • y = cy + r * sin(θ)
  • 示例代码(带行星动画):
<svg width="400" height="400">
  <!-- 大圆轨道 -->
  <circle cx="200" cy="200" r="150" fill="none" stroke="#ccc" />
  <!-- 行星小圆 -->
  <circle id="planet" cx="0" cy="0" r="10" fill="#2ecc71" />
  <script>
    const cx = 200, cy = 200, r = 150;
    let angle = 0;
    function animate() {
      angle += 0.01;
      const x = cx + r * Math.cos(angle);
      const y = cy + r * Math.sin(angle);
      document.getElementById('planet').setAttribute('cx', x);
      document.getElementById('planet').setAttribute('cy', y);
      requestAnimationFrame(animate);
    }
    animate();
  </script>
</svg>

二、用SVG原生方法getPointAtLength()获取点

如果需要获取描边上特定位置的点,可以用这个方法:

  • 先给圆形元素设置id,通过getTotalLength()获取周长,再用getPointAtLength(length)获取对应坐标:
const orbit = document.getElementById('orbit');
const totalLength = orbit.getTotalLength();
// 获取周长1/4位置的点
const point = orbit.getPointAtLength(totalLength / 4);
console.log(point.x, point.y);
  • 按步长遍历取点(比如每10px取一个):
const orbit = document.getElementById('orbit');
const totalLength = orbit.getTotalLength();
const points = [];
for(let i=0; i<=totalLength; i+=10){
  const p = orbit.getPointAtLength(i);
  points.push({x: p.x, y: p.y});
}
// 批量创建小圆
points.forEach(p => {
  const dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
  dot.setAttribute('cx', p.x);
  dot.setAttribute('cy', p.y);
  dot.setAttribute('r', 3);
  dot.setAttribute('fill', '#9b59b6');
  document.querySelector('svg').appendChild(dot);
});

三、将圆形转为<path>后取点

把圆形转成路径格式,再用路径的方法获取坐标:

  • 圆形转路径的格式:M cx-r, cy A r,r 0 1,1 cx+r, cy A r,r 0 1,1 cx-r, cy
  • 示例路径:
<path id="orbitPath" d="M 50,200 A 150,150 0 1,1 350,200 A 150,150 0 1,1 50,200" fill="none" stroke="#ccc" />

后续用法和第二种方法一致,通过getPointAtLength()获取坐标。

内容的提问来源于stack exchange,提问作者Hira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:15:29