要获取 SVG 路径的中心点,您可以使用 `getPointAtLength()` 方法来获取路径上指定长度处的坐标,然后计算所有坐标的平均值。具体步骤如下:
1. 获取路径的总长度,可以使用 `getTotalLength()` 方法。
```js
const path = document.querySelector('path');
const totalLength = path.getTotalLength();
```
2. 使用 `getPointAtLength()` 方法获取路径上某个位置的坐标。这里我们选择获取路径中点的坐标,因此需要将总长度除以 2。
```js
const midpoint = path.getPointAtLength(totalLength / 2);
```
3. 将路径的起点和终点也添加到坐标数组中,并计算所有坐标的平均值。
```js
const startPoint = path.getPointAtLength(0);
const endPoint = path.getPointAtLength(totalLength);
const coordinates = [startPoint, midpoint, endPoint];
const centerX = coordinates.reduce((sum, point) => sum + point.x, 0) / coordinates.length;
const centerY = coordinates.reduce((sum, point) => sum + point.y, 0) / coordinates.length;
```
现在,`centerX` 和 `centerY` 变量中存储了路径的中心点坐标。请注意,如果路径包含多个子路径,则需要分别计算每个子路径的中心点,并将它们合并为一个整体中心点。