Without CSS, the Web Animation API makes the web even more lively
One key (API) puts every hole
Animation on the web has long been divided into 4 specific areas:
- High-performance CSS transitions and animations provide keyframing, but are also very time-consuming to build, and only provide basic start-and-end controls in CSS and JavaScript . This easily limits the animation of simple feedback UI, loops, and animation page load.
- SMIL (Synchronized Multimedia Integration Language) is also very powerful, but too heavy in syntax and incomplete browser support. The tool is also limited to controlling elements only in the SVG context.
- JavaScript allows element controls directly, but does not comprehend 'designer-friendly' functions such as keyframes or easing, lack of native optimization and performance not as good as CSS. Canvas API animation is great, but it does not thoroughly understand the underlying principles of animation, and it is impossible to animate the arbitrary (arbitrary) DOM elements.
- JavaScript animation frameworks like Greensock , with the desire to overcome the lack of animation in JavaScript, but have all the weaknesses in the frameworks: page load, performance, and learn new syntax.
The Web Animations API has a bigger ambition: combining the best features of all the above tools into a single body , eliminating all omissions, giving a thorough understanding of keyframes. , easing, and element control in JavaScript, with the same on-screen performance as CSS. With specifications now supported in Chrome and Firefox, along with published and done research with other browsers, including Safari and Edge . Available with robust polyfil . With such advantages, it is time to pay attention to the Web Animations API.
The Web Animations API helps make animation a staple of web design, opening gates to vendor-optimized performance and 3rd party tooling.
– Rachel? Nabors (@rachelnabors) September 29, 2016
Keyframes in JavaScript
Consider one of the simplest examples of keyframe animations: just move a red ball element from one side to the other. No matter which technique we use, the element will stay the same:
1 | <div id = "redball"> </div> |
The original CSS is the same:
1 2 3 4 5 6 7 8 9 10 11 12 13 | body { margin: 0; background: # 000; overflow: hidden; min-height: 100vh; } #redball { background: red; width: 30vmin; height: 30vmin; border-radius: 50%; } |
I used the vmin
unit to keep the element symmetrical, while responding to the view point size.
In CSS, to move the ball from one side to another page, we will need:
1 2 3 4 5 6 7 8 | @keyframes moveBall { from { transform: translateX (-20vw); } big transform: translateX (100vw); } } |
Animation will be called after declaring red ball element:
1 2 3 | #redball { animation: moveBall 3s infinite; } |
Results illustrated on codepen:
See the Pen Basic Red Ball Animation by SitePoint ( @SitePoint ) on CodePen .
At this point, there are some things to keep in mind about animation, in which, easing (slow and slow at the end) is built in automatically.
About Web Animations API
Maintain the original HTML and style, remove CSS animation and replace JavaScript (using the Web Animation API) to achieve the same purpose:
1 2 3 4 5 6 7 8 9 | var moveBall = document.getElementById ('redball'). animate ([{ transform: 'translateX (-20vw)' }, { transform: 'translateX (100vw)' }], { duration: 3000, iterations: Infinity, easing: 'ease' }); |
You can see that the syntax receiving animation is mostly similar to CSS, but manifests itself as an object with an array representing keyframes. We don't have to explicitly declare to
or from
in keyframe – JavaScript will automatically distribute the keyframe to us, even declaration (declaration) is also possible.
Animation is still not running; As in CSS, we have to call out:
1 | moveBall.play (); |
The keyframe part of the syntax will even become easier with future browsers, when aspects of CSS transformation syntax (which were previously values ) can be used as properties :
1 | translateX: -20vw; |
Changing to this specification is already available in Chrome Canary, but it must be a two-to-one chance that the new syntax is supported by all modern browsers.
Some things to note about scripts:
- JavaScript updates animation timing in milliseconds, not standard CSS seconds (CSS also uses milliseconds, as long as you add the
ms
suffix to the timing value). - The Web Animations API indicates the number of iterations as
iterations
, not the CSS 'interation-countproperty (when defined individually); keyword is
Infinity(I capitalized) for the number of iterations, not
infiniteof CSS.
- In the Web Animations API, easing is default linear
, so in our demo, we define
easeas the default value for CSS animation.
The result is similar to CSS animation.
See the Pen Basic Red Ball Animated Web Animation API by SitePoint ( @SitePoint ) on CodePen .
Of course, copying CSS animations like this in JavaScript doesn't really make the most of the flexibility of this scripting language; To illustrate more clearly, we will create a more complete animation.
Dealing Images
Not long ago I had studied making an animation "scattering" a series of images on the web, like snapping a card playing on a table. Writing an animation for each card in traditional CSS will take a lot of time, and almost always bring the same effect. Instead, I use Web Animation API, this is the perfect tool for this request.
Progressive Cards
We want the image to be displayed whether JavaScript or Web Animations API is valid or not. So, we'll start by adding a series of images to the page:
1 2 3 4 5 6 7 8 | <div class = "shuffle expose"> <img src = "bridgefog.jpg" alt> <img src = "daisyface.jpg" alt> <img src = "drowninghand.jpg" alt> <img src = "firefigure.jpg" alt> <img src = "shellhand.jpg" alt> <img src = "waterfeet.jpg" alt> </div> |
We leave the alt value blank for the image to keep the code clean; in production version, they will be filled in the description. These photos were taken by .tafo. , is used under the Creative Commons Attribution-NoDerivs 2.0 Generic license .
We can add a bit of CSS to display images with animation if the no-JavaScript condition is true:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @keyframes reveal { big opacity: 1; } } .shuffle { min-height: 100vh; position: relative; } .shuffle img { width: 33%; opacity: 0; } .expose img { animation: reveal 1s forwards; } |
The appearance time of each image can be delayed with:
1 2 3 4 | .expose img: nth-child (1) {animation-delay: 1s; } .expose img: nth-child (2) {animation-delay: 2s; } .expose img: nth-child (3) {animation-delay: 3s; } ... |
Typically, tan can automate these declarations with Sass or another processing tool.
The image will have borders if the parent element has the class webanim
, applied to JavaScript:
1 2 3 | div.webanim img { border: 1.4vw solid #eee; } |
JavaScript
We will add the script at the end of the page. There will be some random values in the animation, so I will create a separate function for this purpose:
1 2 3 | function getRandom (min, max) { return Math.random () * (max - min) + min; } |
Then I will collect the image container and all images in it, and set an incrementor variable:
1 2 3 | var imgContainer = document.querySelector (". expose"), imgSeq = document.querySelectorAll (". shuffle img"), i = 1; |
Then, I will remove the expose class (the image has no animation and opacity at
0 level) because CSS animation only works if the container has a
expose class:
1 2 | imgContainer.classList.remove ("expose"); imgContainer.classList.add ("webanim"); |
Class webanim will place the image in the frame.
Most scripts take place in the forEach loop in a function. I will call the function once all image data has been loaded (as opposed to the image node that merely appears in the DOM) with David DeSandro's
imagesLoaded script :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function racknstack () { Array.prototype.forEach.call (imgSeq, function (photo) { setTimeout (function () { photo.style.position = "absolute"; photo.style.width = getRandom (33, 45) + "%"; photo.style.left = getRandom (-5, 65) + "%"; photo.style.top = getRandom (-6, 60) + "vh"; var animate = photo.animate ([{ opacity: '0', transform: 'rotate (' + getRandom (-12, 12) + 'deg) scale (1.2)', boxShadow: '0 0 12px 12px rgba (0.0,0, .3)' }, { opacity: '1', transform: 'rotate (' + getRandom (-8, 8) + 'deg)', boxShadow: '0 0 6px 6px rgba (0.0,0, .3)' }], { duration: 2000, fill: 'forwards' }); }, 1800 * i) i ++; }) } |
As above, we must first call the function:
1 | imagesLoaded (imgSeq, racknstack); |
Result:
See the Pen Random Stacked Images w / WebAnim API & Progressive JS by SitePoint ( @SitePoint ) on CodePen .
Accordingly, this function:
- set the image to the absolute position;
- Generate random widths for images (percentage values, so images remain flexible and responsive)
- Generating random locations for images (including negative locations may appear, meaning images appear only slightly off the viewport's border)
- Animate images with Web Animation API. The keyframe will blur the image from 0
to the solid opacity, when rotating the image.
We need to fill forward` because we want the image to remain in the final state after the animation has been completed.
Join the largest Web programming community in Vietnam: Vietnamwebsummit.com
From strength to strength
Web Animation API is still developing rapidly:
- The working draft is currently being completed quickly, with a large number of components supported by Chrome and Firefox.
- You can also drop polyfill independently, to support browsers that have not yet added this spec.
Conclude
As you can see, Web Animation API allows us to move from specific properties, declarations, step by step of CSS animation to the flexible, unconditional direction of JavaScript, thereby giving expressive animations (vivid), random (random), and high performance.