--- title: 使用 SMIL 的 SVG 动画 slug: Web/SVG/SVG_animation_with_SMIL tags: - Firefox 4 - Gecko 2.0 - 动画 translation_of: Web/SVG/SVG_animation_with_SMIL ---
Chrome 45弃用了SMIL,以利于CSS动画以及Web动画。
Firefox 4 利用Synchronized Multimedia Integration Language (SMIL)引入了对动画SVG的支持。SMIL允许你:
只要在一个SVG元素内添加一个SVG元素比如说
自从Chrome 45,SMIL动画被弃用了,以利于CSS动画和Web动画。
如果你想在同一个元素里变动更多的属性,只要添加更多的{{ SVGElement("animate") }}元素。
<!DOCTYPE html> <html> <head> <title>Attribute Animation with SMIL</title> </head> <body> <svg width="300px" height="100px"> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1"> <animate attributeName="cx" from="0" to="100" dur="5s" repeatCount="indefinite" /> </circle> </svg> </body> </html>
元素用于变动属性。这个新元素是必要的,否则我们就不能让一个简单的、仅仅是一个数字的属性比如说x动起来。旋转属性看起来是这样的:rotation(theta, x, y),这里theta是以角度数计量的角度,x和y都是绝对位置。在下面的示例中,将变动旋转的中心以及角度。
<!DOCTYPE html>
<html>
<head>
<title>SVG SMIL Animate with transform</title>
</head>
<body>
<svg width="300px" height="100px">
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<rect x="0" y="50" width="15" height="34" fill="blue" stroke="black" stroke-width="1" transform="rotation">
<animateTransform
attributeName="transform"
begin="0s"
dur="20s"
type="rotate"
<!-- Rotate from 0 to 360 degrees, and move from 60 to 100 in the x direction. -->
from="0 60 60"
to="360 100 60"
<!-- Keep doing this until the drawing no longer exists. -->
repeatCount="indefinite"
/>
</rect>
</svg>
</body>
</html>
在这个示例中,一个蓝色的圆球在左右边界之间弹动,一次又一次,永不停息。这个动画是用{{ SVGElement("animateMotion") }}元素操纵的。在这个例子中,我们建立了一个由MoveTo命令和Horizontal-line命令、Z命令构成的路径,MoveTo命令命令指定动画路径的起始点,而Horizontal-line命令把圆移到右边300像素处,Z命令闭合路径,建立一个回到起始点的回路。把repeatCount属性的值设置为indefinite,我们指明了反复循环的动画,只要SVG图像还存在就会一直循环下去。
<!DOCTYPE html>
<html>
<head>
<title>SVG SMIL Animate with Path</title>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px">
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
<animateMotion path="M 0 0 H 300 Z" dur="3s" repeatCount="indefinite" />
</circle>
</svg>
</body>
</html>
略有改变的示例,其运动路径是一条曲线,沿着路径的方向运动。
<!DOCTYPE html>
<html>
<head>
<title>SVG SMIL Animate with Path</title>
</head>
<body>
<svg width="300px" height="100px">
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<rect x="0" y="0" width="20" height="20" fill="blue" stroke="black" stroke-width="1">
<animateMotion path="M 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80Z"
dur="3s" repeatCount="indefinite" rotate="auto">
</rect>
</svg>
</body>
</html>