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 is a rotating rectangle, with changing color.

Code

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

<script defer src="web_animation.js"></script>
document.getElementById("mxtvx").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("idh2JCF").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: Transform

It's also in SVG.

〔see SVG: Coordinate Transformation

Example 3, change size

document.getElementById("idHKWwm").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

Animation, CSS, SVG, Web