How to control CSS animations (animations) and transitions (transitions) using JavaScript

Source: Internet
Author: User
Tags abs in degrees


Zach e-Mail told me that on the stack overflow forums like this, he often encountered some questions about JavaScript controlling CSS animations, and gave me a few examples. I've been planning to write about this for a long time, so I'm glad to have Zach put it up and prompted me to write this tutorial. Sometimes web developers think that CSS animations are more difficult to understand than JavaScript animations. Although CSS animation has its limitations, its performance is much more efficient than most JavaScript libraries because it can be accelerated with hardware! The effect can definitely exceed our expectations.


CSS animations and transitions, together with a bit of JavaScript, enable hardware-accelerated animations, and their interactions are more efficient than most JavaScript libraries.



So, let's get started! The Little friends can't wait!


Note: animations (animation) and transitions (transitions) are differentThe CSS Transitions (transition) is applied to the attribute changes specified by the element, which gradually transitions over time to the value that is ultimately needed, while the CSS animations (animation) simply executes the previously defined operation when applied, providing finer granularity of control. In this article, we will explain the above content separately. control CSS Transition (transitions)  In the programming forum, there are countless questions about the transition (transition) triggering and pausing. Using JavaScript makes it easy to solve these questions. Triggering the element's Transiton (transition), toggles the element's class name to trigger the element's transition (transition) Pause element's transition (transition), where you want to pause the transition point, Use getComputedStyle and GetPropertyValue to get the corresponding CSS property value for the element, and then set the corresponding CSS property of the element equal to the value of the CSS property you just acquired. Here is an example of this method. Execution effect: Http://cdpn.io/GokAm the same technique can be used in more advanced ways. The following example also triggers the transition (transition) of an element by changing the class name, but this time the current zoom rate can be traced.


Execution Effect: http://cdpn.io/FIlHe


Notice what we've changed this time is the value of background-size. There are a number of different CSS properties that can be applied to transitions and animations, and these properties typically have numeric or color values. About CSS Transitions (transition), Rodney Rehm also wrote a very good article, which can be accessed here. using the CSS "callback function"  Some of the most useful but little-known JavaScript techniques are the use of listener DOM events to control CSS transitions (transitions) and animations (animations). such as: Animationend,animationstart and animationiteration related to animations (animation); Transitonend related to Transitions (transition). You may have guessed what they do. These animation events are triggered at the end of an element's animation, at the beginning, or when an iteration is completed. The current use of these events also requires the addition of a browser prefix, so in this demo we use the method called Prefixedevent developed by Craig Buckler. The parameters of the method have element (element), type (types), and callback (callback) to achieve cross-browser compatibility. Here is one of his articles using JavaScript to capture CSS animations (animations). Here is another article about determining which event to trigger by judging the animation name. This demo wants to achieve the stop animation when the mouse hovers and enlarge the heart pattern.


Execution Effect: HTTP://CDPN.IO/RMDDX


The pure CSS version jumps when the mouse hovers, unless you move the mouse at the right time, or it jumps to a specific state before it expands to the final hover state. The JavaScript version is smooth, and it makes the animation complete before applying the new amplification state so that the mouse hovers without jumping. control CSS Animation (animation)  As we have just learned, we can see events related to element animations: Animationstart,animationiteration,animationend. But if we want to change the animation in the process of CSS Animation (animation), we need a little bit of skill! Animation-play-state PropertyWhen you want to pause during the execution of the animation, and then let the animation proceed. The Animation-play-state property of CSS is very useful at this point. You can change the CSS (note your prefix) with javascript like this:

element.style.webkitAnimationPlayState ="paused";element.style.webkitAnimationPlayState ="running";
However, when you use Animation-play-state to pause a CSS animation, the elements in the animation are distorted in the same way. You cannot make this deformation pause in a state, deform it, restore it, or expect it to return to smooth operation from a new state of deformation. In order to achieve these controls, we need to do some more complex work. gets the percentage of the current KeyValueUnfortunately, there is no way to get the "percent complete" of the current CSS animation keyframe at this stage. The best way to get the approximate value is to use the SetInterval function to iterate through the animation 100 times. Its essence is: the duration of the animation (in milliseconds)/100. For example, if the animation is 4 seconds long, the resulting setinterval execution time is every 40 milliseconds (4000/100). This is not ideal because the function actually runs much less often than every 40 milliseconds. I found it more accurate to set it to 39 milliseconds. But this is not a good implementation, because it relies on the browser, not all browsers can get the perfect effect. Gets the CSS property value for the current animationIdeally, we select an element that uses CSS animations, delete the element's current animation and add a new animation to it, allowing it to start a new animation from its current state. But the real situation is complicated. Here we have a demo to test the techniques for getting and changing the "middle stream" of CSS animations. The animation lets an element move along a circular path, starting at the center (or "12-point") position of the circle's top. When the button is clicked, the starting position of the element becomes the position where the element is currently moved. The element will continue to move along the same path as before, but now the "start" position becomes the position where the element is moved when you press the button. By turning the color of the element into red at the first keyframe of the animation, the position of the element animation start point is changed.


Execution Effect: Http://cdpn.io/GwBJa


The same concept is used in this example of StackOverflow. We need to be very deep to finish! We're going to go into the style sheet itself and find the original animation.




You can use Document.stylesheets to get a collection of style sheets associated with a page, and then get a specific style sheet through a for loop. Here's how to use JavaScript to find a Csskeyframerules object for a particular animated value:




function findKeyframesRule(rule){
var ss = document.styleSheets;
for(var i = 0;i < ss.length;++i){
for(var j = 0;j


Once we invoke the above function (for example, Var keyframes= findkeyframesrule (Anim)), we can get the animation length of the object by Keyframes.cssRules.length (the total number of keyframes in this animation). Then use JavaScript's. Map method to filter out "%" on each keyframe value you get, so that JavaScript can use these values as numbers.


// Makes an array of the current percent values
// in the animation
var keyframeString = [];
for(var i = 0; i < length; i ++)
{
keyframeString.push(keyframes[i].keyText);
}
// Removes all the % values from the array so
// the getClosest function can perform calculations
var keys = keyframeString.map(function(str) {
return str.replace('%', '');
});
Here, the keys is an array containing all the animated keyframe values. Change the actual animation (finally!) )During the loop animation, we need two variables: one to track how many degrees were moved from the nearest starting position and the other to track how many degrees were moved from the original starting position. We can change the first variable by using the SetInterval function (the time that is consumed when the ring moves in degrees). We can then use the following code to update the second variable when the button is clicked.




totalCurrentPercent += currentPercent;
// Since it's in percent it shouldn't ever be over 100
if (totalCurrentPercent > 100) {
totalCurrentPercent -= 100;
}


We can then use the following function to find the key frame value closest to the current total percent value in the keyframe array we obtained earlier.


function getClosest(keyframe) {
// curr stands for current keyframe
var curr = keyframe[0];
var diff = Math.abs (totalCurrentPercent - curr);
for (var val = 0, j = keyframe.length; val < j; val++) {
var newdiff = Math.abs(totalCurrentPercent - keyframe[val]);
// If the difference between the current percent and the iterated
// keyframe is smaller, take the new difference and keyframe
if (newdiff < diff) {
diff = newdiff;
curr = keyframe[val];
}
}
return curr;
}


To get the position value of the first keyframe of the new animation, we can use the JavaScript's. IndexOf method. We then redefine the keyframe by removing the original Keyframe definition based on this value.


for (var i = 0, j = keyframeString.length; i < j; i ++) {
keyframes.deleteRule(keyframeString[i]);
}
Next, we need to convert the degree value of the circle to the corresponding percent value. We can get through the position value of the first keyframe with 3.6 simple multiplication (because 10 0 * 3.6 = 360). Finally, we create a new rule based on the variables obtained above. There is a 45-degree difference between each rule because we have eight different keyframes in the loop, 360 (the degree of a circle) divided by 8 is 45.
// Prefix here as needed
keyframes.insertRule("0% {
-webkit-transform: translate(100px,100px) rotate(" + (multiplier + 0) + "deg)
translate(-100px,-100px) rotate(" + (multiplier + 0) + "deg);
background-color:red;
}");
keyframes.insertRule("13% {
-webkit-transform: translate(100px,100px) rotate(" + (multiplier + 45) + "deg)
translate(-100px,-100px) rotate(" + (multiplier + 45) + "deg);
}");
...continued...
We then reset the current percent value by setinterval so that it can run again. Note that the WebKit prefix is used, in order to make it compatible with more browsers, we need to do some UA sniffing to determine which prefix to use:
// Gets the browser prefix
var browserPrefix;
navigator.sayswho= (function(){
var N = navigator.appName, ua = navigator.userAgent, tem;
var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s(.?\d+(.\d+))/i);
if(M && (tem = ua.match(/version\/([.\d]+)/i))!= null) M[2] = tem[1];
M = M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
M = M[0];
if(M == "Chrome") { browserPrefix = "webkit"; }
if(M == "Firefox") { browserPrefix = "moz"; }
if(M == "Safari") { browserPrefix = "webkit"; }
if(M == "MSIE") { browserPrefix = "ms"; }
})();


If you want to study further, you can visit Russell Uresti on StackOverflow posts and the corresponding case.


Animations (animation) turn into Transitions (transition)  




As we can see, using JavaScript makes it easy to manipulate CSS transitions (transitions). If you don't get the results you want by using CSS animations (animation), you can try to turn it into a CSS transitions (transition). They have about the same amount of code from the CSS code, but using Transiton can be easier to set up and edit.




The biggest problem with converting CSS animations (animations) to CSS transitions (transitions) is that when we convert animation-iteration to an equivalent transition command, transitons (transition) There is no direct equivalent command. One of the tips for our spin demos is to multiply X by transition-duration and rotation (translators: the rotation values of the x and Y axes, respectively). Then you need to use the style class to trigger the animation, because if you change these properties directly on the element, there will be no transitions. You need to add the class name to the element to trigger the transition (simulate animation). In our example, we implemented the page load:


Execution Effect: http://cdpn.io/IdlHx


using CSS matricesYou also use Cssmatrix to manipulate CSS animations (animations). Like what:




vartranslated3D =newWebKitCSSMatrix(window.getComputedStyle(elem,null).webkitTransform);


But this process can be confusing, especially for those who have just started using CSS animations (animations).


For more information on CSS matrices, see the documentation (although help is not too large), this tool allows you to manipulate the values of matrices, or articles on this topic. Reset CSS Animations (animation)The method of implementing this technique can be found from CSS tricks. Brain  Before you start coding, thinking about and planning how transitions or animations are performed should be the best way to reduce your problems and achieve the results you want. Better than your Google search solution when you're having problems! Although the techniques and techniques summarized in this article are not necessarily the best way to create animations in your project, it's worth trying to understand (I can only help here ...).  )。 For example, this small example solves the problem with only HTML and CSS, and you may start thinking about using JavaScript to solve it. We want a constantly rotating graphic to rotate in the opposite direction when the mouse hovers over it. You may have skipped this article by using the Animationiteration event directly to implement this animation. However, a more effective and better solution is to use CSS and add content elements. The trick is to get the rotational speed X of the rotated figure, and when the mouse hovers, let its parent rotate in the opposite direction (in the same position) at twice X. The rotation of the two directions interacts, resulting in the desired reverse rotation effect. Execution effect: Http://cdpn.io/sFnyD the same concept is used in this example of StackOverflow. RELATED LINKSYou may be interested in the relevant stuff. animo.js– powerful gadget for managing CSS animations thank God We have A specification! –smashing Magazine's article on Transition skills Summary1. getComputedStyle is helpful for working with CSS transitions (transitions) 2. Transitionend and its related events are very helpful for using JavaScript to manipulate CSS transitions (transitions) and animations (animations) 3. You can change the value of the current CSS animation by using JavaScript to get the style sheet, but the operation is more complex. 4. It is often easier to manipulate CSS transitions (transitions) with JavaScript than to manipulate CSS animations (animations). 5. Working with CSS matrices is more painful, especially for beginners. 6. Thinking about what to do and how to plan it is the key to animation coding.


How to control CSS animations (animations) and transitions (transitions) using JavaScript


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.