我如何获取这个路径的中心点

动态 未结 0 107
小小草
小小草 LV1 2023年9月23日 23:40 发表
要获取 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` 变量中存储了路径的中心点坐标。请注意,如果路径包含多个子路径,则需要分别计算每个子路径的中心点,并将它们合并为一个整体中心点。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复