写一个svg 沿着路径线条移动的示例
时间: 2024-02-13 10:59:39 浏览: 25
好的,以下是一个简单的 SVG 沿着路径线条移动的示例代码:
```html
<svg width="200" height="200">
<path id="path" stroke="#333" stroke-width="2" fill="none" d="M 50,50 L 150,50 L 150,150 L 50,150 L 50,50" />
<circle id="circle" cx="50" cy="50" r="10" fill="red">
<animateMotion dur="4s" repeatCount="indefinite">
<mpath xlink:href="#path" />
</animateMotion>
</circle>
</svg>
```
这段代码中,我们定义了一个路径线条 `path`,并使用 `circle` 元素作为要移动的对象。在 `circle` 元素中,我们使用 `animateMotion` 元素来实现沿着路径移动的动画效果。`mpath` 元素用于指定要沿着哪个路径移动,这里我们指定为 `path` 路径线条。
你可以将这段代码复制到一个 HTML 文件中进行测试,或者在在线 SVG 编辑器中进行测试,例如 Codepen 或 JSFiddle。
相关问题
写一个svg 线 沿着路径移动的示例
好的,以下是一个简单的 SVG 线沿着路径移动的示例代码:
```html
<svg width="200" height="200">
<path id="path" stroke="#333" stroke-width="2" fill="none" d="M 50,50 L 150,50 L 150,150 L 50,150 L 50,50" />
<line id="line" x1="50" y1="50" x2="150" y2="150" stroke="red" stroke-width="2">
<animateMotion dur="4s" repeatCount="indefinite">
<mpath xlink:href="#path" />
</animateMotion>
</line>
</svg>
```
这段代码中,我们定义了一个路径线条 `path`,并使用 `line` 元素作为要移动的对象。在 `line` 元素中,我们使用 `animateMotion` 元素来实现沿着路径移动的动画效果。`mpath` 元素用于指定要沿着哪个路径移动,这里我们指定为 `path` 路径线条。
你可以将这段代码复制到一个 HTML 文件中进行测试,或者在在线 SVG 编辑器中进行测试,例如 Codepen 或 JSFiddle。
写一个 光点沿着svg路径移动的示例
好的,以下是一个简单的光点沿着 SVG 路径移动的示例:
首先,我们需要一个 SVG 路径,并在路径上添加一个“marker”元素,用于表示光点。代码如下:
```html
<svg width="400" height="400">
<path id="motionPath" d="M 100 100 Q 200 50 300 100 Q 350 150 300 200 Q 200 250 100 200 Q 50 150 100 100" fill="none" stroke="#ccc" stroke-width="2" />
<marker id="point" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<circle cx="5" cy="5" r="2" fill="yellow" />
</marker>
<circle id="movingPoint" cx="100" cy="100" r="5" fill="red" />
</svg>
```
接下来,我们使用 JavaScript 来实现光点沿着路径移动的效果。具体实现如下:
```javascript
// 获取路径元素和光点元素
const motionPath = document.querySelector('#motionPath');
const movingPoint = document.querySelector('#movingPoint');
// 获取路径的总长度
const pathLength = motionPath.getTotalLength();
// 设置光点元素的“marker-end”属性为我们定义的marker元素
movingPoint.setAttribute('marker-end', 'url(#point)');
// 定义动画函数
function animate() {
// 获取当前时间
const currentTime = performance.now();
// 计算路径上的位置
const pointAtLength = motionPath.getPointAtLength(currentTime / 10 % pathLength);
// 更新光点的位置
movingPoint.setAttribute('cx', pointAtLength.x);
movingPoint.setAttribute('cy', pointAtLength.y);
// 循环调用动画函数
requestAnimationFrame(animate);
}
// 开始动画
animate();
```
在上面的代码中,我们使用了 `performance.now()` 函数获取当前时间,并计算出路径上对应的位置。然后,我们更新了光点的位置,并使用 `requestAnimationFrame()` 循环调用动画函数。
现在,您可以在浏览器中运行这段代码,看到一个光点沿着 SVG 路径移动的效果。