Web Animation

By Xah Lee. Date: . Last updated: .

Web animation is a W3C standard that allows JavaScript to directly script CSS Animation.

As of 2017-12, Web Animation is supported in Google Chrome and Firefox only. Not supported in Safari nor Edge. Use Google Chrome or Firefox to see example here.

Here's a rotating rectangle, with changing color.

Here's the HTML code

<svg viewBox="-50 -50 100 100">
<rect id="x68595" x="0" y="0" width="10" height="40" />

<script defer src="web_animation.js"></script>

That's a rectangle, with width 10 and height 40. The view box is 100 by 100, and left top corner has coordinate -50 -50. So, center is 0 0.

Here's JavaScript:

        { transform: "rotate(0deg)", fill:"red" },
        { transform: "rotate(360deg)", fill:"blue" }
        duration: 4000,
        iterations: 100

The method animate takes 2 arguments:

First argument is called a keyframe object. It holds data about key frames. Each key frame is data about position, orientation, color, etc, of the element. (it is similar to keyframe of CSS Animation)

Second argument is called animation effect property. It is data about animation duration, iteration, forward/backward, etc.

If you are not familiar, you should understand CSS animation first. Because many concepts is borrowed from it.


Example 2, More Keyframes

Now, let's add more keyframes.

        { transform: "rotate(0deg)", fill:"black" },
        { transform: "rotate(180deg)", fill:"grey" },
        { transform: "rotate(360deg)", fill:"black" }
        duration: 4000,
        iterations: 100

The fill is a SVG shape element property. It's similar to CSS's color. [see SVG: Basic Shape Styles]

The transform is CSS's transform.

[see CSS: 2D Transform]

It's also in SVG.

[see SVG: Coordinate Transformation]

Example 3, change size

        { transform: "rotate(0deg) scale(0,0)", fill:"red" },
        { transform: "rotate(360deg) scale(1, 1)" , fill:"blue" }
        duration: 4000,
        iterations: 100

Keyframe Object


SVG Topics

  1. SVG: Basic Examples
  2. SVG Path Tutorial
  3. SVG Path: Elliptical Arc
  4. SVG: Specifying Styles
  5. SVG: Basic Shape Styles
  6. SVG: Viewport
  7. SVG: viewBox, User Coordinate
  8. SVG: Coordinate Transformation
  9. SVG: Text Element Tutorial
  10. SVG: Structure Elements
  11. JS: Scripting SVG, Basic Example
  12. JS: SVG Clock
  13. SVG Animation
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon