svg 使用写一个 animateMotion 让圆沿着线移动的动画
时间: 2024-02-12 10:07:23 浏览: 27
可以使用 SVG 的 `animateMotion` 元素来实现圆沿着线移动的动画。具体实现步骤如下:
1. 在 HTML 中创建 SVG 元素,并添加一个圆和一条直线。可以使用以下代码:
```html
<svg width="500" height="500">
<circle id="dot" cx="50" cy="50" r="5" fill="red" />
<line id="line" x1="50" y1="50" x2="100" y2="100" stroke="black" />
</svg>
```
2. 在 SVG 中添加一个 `path` 元素,用于描述圆沿着直线移动的路径。可以使用以下代码:
```html
<path id="path" d="M 50 50 L 100 100" />
```
3. 在 `circle` 元素中添加一个 `animateMotion` 元素,指定运动的路径为 `path` 元素,并设置动画持续时间。可以使用以下代码:
```html
<circle id="dot" cx="50" cy="50" r="5" fill="red">
<animateMotion dur="2s" repeatCount="indefinite">
<mpath xlink:href="#path" />
</animateMotion>
</circle>
```
4. 最后,使用 CSS 样式表中的 `path` 元素来隐藏路径线。可以使用以下代码:
```css
path {
stroke: none;
fill: none;
}
```
这样,圆就可以沿着直线移动了。完整的代码如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<title>SVG animateMotion Demo</title>
<style>
path {
stroke: none;
fill: none;
}
</style>
</head>
<body>
<svg width="500" height="500">
<circle id="dot" cx="50" cy="50" r="5" fill="red">
<animateMotion dur="2s" repeatCount="indefinite">
<mpath xlink:href="#path" />
</animateMotion>
</circle>
<line id="line" x1="50" y1="50" x2="100" y2="100" stroke="black" />
<path id="path" d="M 50 50 L 100 100" />
</svg>
</body>
</html>
```
注意:以上代码中使用了 `xlink:href` 属性来指定路径的链接,这是因为 SVG 1.1 版本中规定的,如果你使用的是 SVG 2 版本,则需要使用 `href` 属性来指定路径的链接。