<animateMotion>
标签可以嵌套在任何SVG元素内部,它会使得该元素沿着一个指定的路径移动。
<animateMotion>
标签的属性
path
: 定义元素移动的路径。dur
: 动画持续时间。begin
: 动画开始时间。fill
: 动画完成后元素的状态。repeatCount
: 动画重复的次数。
示例1: 沿直线路径移动
<svg width="200" height="200">
<!-- 使用 animateMotion 标签使圆形沿直线路径移动 -->
<circle cx="10" cy="10" r="5" fill="red">
<animateMotion dur="2s" repeatCount="indefinite" path="M10,10 H190" />
</circle>
</svg>
这个例子中,圆形会无限次数地沿着水平路径从左向右移动。
示例2: 沿曲线路径移动
<svg width="200" height="200">
<!-- 使用 animateMotion 标签使圆形沿曲线路径移动 -->
<circle cx="10" cy="10" r="5" fill="green">
<animateMotion dur="4s" repeatCount="indefinite" path="M10,80 Q100,10 190,80 T380,160" />
</circle>
</svg>
这个例子中,圆形会无限次数地沿着一个复杂的曲线路径移动。
示例3: 使用begin
和fill
<svg width="200" height="200">
<!-- 使用 animateMotion 标签并设置 begin 和 fill 属性 -->
<circle cx="10" cy="10" r="5" fill="blue">
<animateMotion begin="1s" fill="freeze" path="M10,10 H190" dur="2s" />
</circle>
</svg>
这个例子中,圆形会在1秒后开始沿直线移动,并在动画结束后保持在终点位置。
示例4: 结合<mpath>
使用
<svg width="200" height="200">
<!-- 定义一个路径 -->
<path id="myPath" fill="none" stroke="black" d="M20,20 C20,100 200,100 200,20" />
<!-- 使用 animateMotion 标签结合 <mpath> 元素 -->
<rect x="0" y="0" width="10" height="10" fill="orange">
<animateMotion dur="6s" repeatCount="indefinite">
<mpath href="#myPath" />
</animateMotion>
</rect>
</svg>
这个例子中,矩形会无限次数地沿着一个预定义的曲线路径移动。
示例5: 结合rotate
属性使用
<svg width="200" height="200">
<!-- 使用 animateMotion 标签并结合 rotate 属性 -->
<circle cx="10" cy="10" r="5" fill="purple">
<animateMotion path="M10,10 C100,10 100,190 10,190" dur="6s" rotate="auto" repeatCount="indefinite" />
</circle>
</svg>
这个例子中,圆形会无限次数地沿着一个闭合的曲线路径移动,并且会自动旋转以沿路径前进。
<animateMotion>
高级属性
keyPoints
: 定义沿路径的位置的百分比,与path
属性一起使用。keyTimes
: 定义动画中各个关键帧发生的时间,与dur
属性一起使用。calcMode
: 定义动画中值之间的插值方法。keySplines
: 定义每个关键帧之间动画的速度曲线,与calcMode="spline"
一起使用。
示例1: 使用keyPoints
和keyTimes
<svg width="200" height="200">
<!-- 定义一个路径 -->
<path id="myPath" fill="none" stroke="black" d="M10,10 Q100,50 190,10" />
<!-- 使用 animateMotion 标签结合 keyPoints 和 keyTimes -->
<rect width="20" height="20" fill="red">
<animateMotion dur="4s" repeatCount="indefinite" keyPoints="0;0.5;1" keyTimes="0;0.5;1">
<mpath href="#myPath" />
</animateMotion>
</rect>
</svg>
这个例子中,矩形会沿着路径在4秒内从起点移动到中点,然后到终点,keyPoints
定义了沿路径的位置,keyTimes
定义了时间点。
示例2: 使用calcMode
和keySplines
<svg width="200" height="200">
<!-- 定义一个路径 -->
<path id="anotherPath" fill="none" stroke="black" d="M10,190 Q100,150 190,190" />
<!-- 使用 animateMotion 标签结合 calcMode 和 keySplines -->
<circle cx="10" cy="190" r="10" fill="blue">
<animateMotion dur="6s" repeatCount="indefinite" calcMode="spline" keySplines="0.5 0 0.5 1;0.5 0 0.5 1">
<mpath href="#anotherPath" />
</animateMotion>
</circle>
</svg>
这个例子中,圆形会沿着路径以贝塞尔曲线的方式移动,calcMode
设置为spline
,keySplines
定义了动画的速度曲线。