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" />
</svg>

<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:

document.getElementById("x68595").animate(
    [
        { 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.

See:

Example 2, More Keyframes

Now, let's add more keyframes.

document.getElementById("e52627").animate(
    [
        { 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: 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

document.getElementById("e20803").animate(
    [
        { transform: "rotate(0deg) scale(0,0)", fill:"red" },
        { transform: "rotate(360deg) scale(1, 1)" , fill:"blue" }
    ],
    {
        duration: 4000,
        iterations: 100
    }
);

Keyframe Object

https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon