Web Animation API introduction
When we talk about web animation, we naturally think of CSS3 animation, JS animation, SVG animation, jja.animate () and other animation packaging library, according to the actual animation content design to choose a different way to implement, however, each of the existing animation technology has certain shortcomings. For example, CSS3 animations must obtain dynamically changed values through JS, an animation effect scattered in CSS files and JS files is not easy to maintain, setInterval time is often inaccurate and will lag, and the introduction of additional animation encapsulation libraries is not suitable for performance-sensitive businesses.
The history of Web Animation API should also be several years old. However, when making Animation effects, the author just relies on various libraries and seldom thinks about native implementation. As a result, our project relies on various libraries with increasing volume and unknown performance. As front-end developers, we want native JS to support general Animation solutions, and The Web Animation API may be a good solution.
W3C proposed Web Animation API (WAAPI for short) for this reason, it is committed to integrating CSS3 Animation performance, flexible JavaScript, rich Animation library and other advantages, as much as possible Animation control by the native browser. And add many variables, controls, and tuning options that CSS does not have. It provides a common language to describe the Animation of DOM elements. The main methods are Animation, KeyframeEffect, AnimationEvent, DocumentTimeline, and EffectTiming. For a detailed description of the API, you can refer to the MDN documentation at developer.mozilla.org/en-US/docs/…
Using the Web Animations API, we can move interactive Animations from stylesheets to JavaScript, separating presentation from behavior. We no longer need dom-dependent techniques, such as writing CSS properties on elements to control direction. For building custom animation libraries and creating interactive Animations, the Web Animations API can be the perfect tool to get the job done, and you can easily create Animations that work well without resorting to a third-party animation library.
In order to let everybody has a clear understanding of the API, the author in the next series, with five or six examples let everybody understand the API, today I will use this API to achieve a random begin moving pictures, such as the effect we can make a random floating mobile advertising, random walk monsters, and so on in the game, In order to demonstrate the flexibility and power of the Web Animation API, I did not reference any third party libraries such as (JQ) or use the setTimeout and requestAnimationFrame() functions.
This essay is scheduled to take 5 minutes
Animation effects
Before we begin, let’s take a look at the finished animation, as shown in the following example:
The page layout
No matter how random the image moves, we want it to be in a specified container, not a random one. First we define the container in the HTML page:
<div id="container">
</div>Copy the code
Next, define the container style:
body { margin: 0; } div#container { height:500px; width:100%; background: #C6CEF7; } #target { position: absolute; Filter: drop-shadow(-12px 12px 7px rgba(0,0,0,0.5)); }Copy the code
Script part
Access to the container
var container = document.getElementById("container");Copy the code
Loading animation
In order to be more intuitive, I choose a moving GIF image. Since the image takes some time to load, in order not to break the continuity of the animation, we make sure that the image is loaded before we execute the animation. The relevant code is as follows:
var target = document.createElement("img");
target.id = "target";
target.onload = function() {
floatHead();
}
target.src = "walk.gif";
container.appendChild(target);Copy the code
As you can see, in the onload section we load the floatHead() function. Next we will implement this function. This function mainly contains the following functions: create a random position, calculate the movement time, and encapsulate the movement animation.
Random location
We use the math.floor function to change its random position as shown in the following code:
function makeNewPosition() {
var containerVspace = container.offsetHeight - target.offsetHeight,
containerHspace = container.offsetWidth - target.offsetWidth,
newX = Math.floor(Math.random() * containerVspace),
newY = Math.floor(Math.random() * containerHspace);
return [newX, newY];
}Copy the code
For random positions, we’re returning an array of images relative to the container, top,left. Here you need to understand offsetHeight, offsetWidth, which can be understood as the visible height or Width of the div, height or Width of the style + top/bottom padding or left/right padding+ top/bottom border-width or left/right border-width.
Computation time
Animation has a time property, how long does it take us to move the position, let’s say the speed is 0.1 units per millisecond. This function contains two arrays: prev for the original X and Y positions of the current target, and next for the position of the moving target. This function does not perform an exact distance calculation, but only determines the size of the distance moved on the x and y axes by dividing the maximum distance by the speed. Example code is as follows:
function velocity(prev, next) {
var x = Math.abs(prev[1] - next[1]),
y = Math.abs(prev[0] - next[0]),
larger = x > y ? x : y,
speedModifier = 0.1,
time = Math.ceil(larger / speedModifier);
return time;
}Copy the code
Encapsulating motion animation
Next comes the core of our Web Animations API. We use the core API to animate it by adding the two functions we completed above, with the following code for example:
function floatHead() {
var newPos = makeNewPosition(),
oldTop = target.offsetTop,
oldLeft = target.offsetLeft,
target.animate([
{ top: oldTop+"px".left: oldLeft+"px" },
{ top: newPos[0] +"px".left: newPos[1] +"px"}, {duration: velocity([oldTop, oldLeft],newPos),
fill: "forwards"
}).onfinish = function() { floatHead(); }}Copy the code
The Animation of the animate function has two parameters, one is KeyframeEffects arrays and AnimationEffectTimingPropertiesoptions object. Basically, the first parameter maps to @keyframes in your CSS, which you can imagine as @Keyframes in your CSS, such as the following code:
@keyframes emphasis {
0% {
transform: scale(1);
opacity: 1; 30%} {transform: scale(5);opacity:.5;
}
7875.% {
transform: scale(. 667);opacity:.667; 100%} {transform: scale(6);opacity:.6; }}Copy the code
You can put the information in the “{}” sequence in an array; The second parameter is time control timing, including the properties of duration duration, iterations execution times, direction animation direction, easing function and so on. For example:
#toAnimate {
animation: emphasis 700ms ease-in-out 10ms infinite alternate forwards;
}Copy the code
You may also have noticed that we used the onFinish event to make repeated calls to the floatHead function, which is the property of the Animation, to listen for the Animation completion event, and to continue floatHead() if the Animation completes, rather recursively.
The finished code
<html lang="en">
<head>
<style>
body {
margin: 0;
}
div#container {
height:500px;
width:100%;
background: #C6CEF7;
}
#target {
position: absolute;
filter: drop-shadow(7-12 px 12 px px rgba (0,0,0,0.5)); }</style>
<meta charset="UTF-8">
<title>Front-end expert example show - picture random movement</title>
</head>
<body>
<div id="container"></div>
<script>
function makeNewPosition() {
var containerVspace = container.offsetHeight - target.offsetHeight,
containerHspace = container.offsetWidth - target.offsetWidth,
newX = Math.floor(Math.random() * containerVspace),
newY = Math.floor(Math.random() * containerHspace);
return [newX, newY];
}
function velocity(prev, next) {
var x = Math.abs(prev[1] - next[1]),
y = Math.abs(prev[0] - next[0]),
larger = x > y ? x : y,
speedModifier = 0.2,
time = Math.ceil(larger / speedModifier);
return time;
}
function floatHead() {
var newPos = makeNewPosition(),
oldTop = target.offsetTop,
oldLeft = target.offsetLeft;
target.animate([
{ top: oldTop+"px".left: oldLeft+"px" },
{ top: newPos[0] +"px".left: newPos[1] +"px"}, {duration: velocity([oldTop, oldLeft],newPos),
fill: 'forwards'
}).onfinish = function() { floatHead(); }}var container = document.getElementById("container"),
target = document.createElement("img");
target.id = "target";
target.onload = function() {
floatHead();
}
target.src = "walk.gif";
target.width="200";
container.appendChild(target);
</script>
</body>
</html>Copy the code
Compatible with the situation
Finally, let’s talk about your browser compatibility concerns. Here are some of the browser compatibility concerns:
It seems that many of them are partially supported, but not fully supported. The author has personally tested them, and found that the latest version of Google Browser and Firefox on PC run perfectly without any problems. The author’s Safari still doesn’t work, and it doesn’t work on iPhone XS Max.
As a front-end developer, how can I tolerate no effect on the mobile end, in order to use WAAPI (Web Animation API for short) before the modern browser manufacturers have fully followed. We can choose to introduce a Polyfill library for the Web Animation API [github.com/web-animati…] To experience WAAPI in IE/Firefox/Safari and other browsers.
Therefore, we just need to introduce the following JS into the file to have a perfect experience:
<script src="https://cdn.jsdelivr.net/web-animations/latest/web-animations.min.js">
</script>Copy the code
Mobile Browser, Android Browser 5.0 or above and Chrome for Android already support WAAPI. With Polyfill, the author’s mobile phone can finally see the running effect. Wechat’s QQ core browser works perfectly, as does Safari on PC. Can be said to be full platform support, with this library you can rest assured bold use.
section
Well, today’s code is finished, js code is less than 50 lines (note: In order to operate in the mobile terminal, the introduction of the web – animations. Min. Js), you can click on “www.qianduandaren.com/demo/walk/” line preview, the author pro measurement on the iPhone XS Max running well, other phone no, subject to the test of the dear friends, Welcome to the comment section. In the next article, we’ll hand polish a beautiful clock with less than 20 lines of native JS code, so stay tuned.
More exciting content, please pay attention to the wechat “front-end talent” public number!