In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "analyzing the powerful functions of CSS keyframes in JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Create a simple Keyframe Web Animation
To animate Keyframe animation using Web Animation API, simply animate () calls this function on the element:
one
Element.animate (keyframes, Keyframe options)
This function takes two parameters:
Keyframes: a text array containing the JavaScript representation of the required CSS keyframes
KeyframeOptions: text that contains other settings for the animation, such as ease, duration, fill mode, etc.
Take a look at the following simple example, which uses the animate () function instead of CSS keyframes to render the animation:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
Var boxframes = [
{
Transform: 'translateX (0)'
Background: 'red'
BorderRadius: 0
}
{
Transform: 'translateX (200px) scale (.5)'
Background: 'orange'
BorderRadius: 0
Offset: 0.6 / * set explicit point (60%) when frame starts * /
}
{
Transform: 'translateX (400px)'
Background: 'green'
BorderRadius:'50%'
}
]
If we use pure CSS to declare the above, it looks like this:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
@ keyframes animatethebox {
0% {
Transform: translateX (0)
Background: red
BorderRadius: 0
}
60% {
Transform: translateX (200px) scale (.5)
Background: orange
BorderRadius: 0
}
100% {
Transform: translateX (400px)
Background: green
BorderRadius: 50%
}
}
As you can see, the two grammars are very similar, and if you are already familiar with CSS keyframes, there is no problem porting it to JavaScript. Some differences from the JavaScript version are worth remembering:
In the JavaScript version, the attribute string value should be in quotation marks (transform: 'translateX (0)')
Hyphenated attribute names must be converted to camelCase instead of (borderRadius: 0).
Commas instead of semicolons should track each attribute declaration (except for the last attribute)
By default, keyframes set with JavaScript are evenly distributed during playback, with the same time for each Keyframe. However, with offset adding attributes to a Keyframe, we can set the point at which the Keyframe should start playing, such as 0.6 marked by 60%, similar to a Keyframe using pure CSS.
KeyframeOptions parameter
The second argument to the animate () method is a literal that fine-tunes the behavior of the animation. Many options are mapped directly from the animation-* attribute of CSS, such as "animation-delay", "animation-fill-mode", and so on. All properties are optional, if not set, fall back to the default value:
PropertyCSS Property EquivalentDescriptionidnoneOption that sets the name of this Animation to refer back to later in your code.delayanimation-delayThe delay (integer) before the animation starts in milliseconds. Defaults to 0s.directionanimation-directionDefines whether the animation should play as normal, in reverse, or alternate between the two. Possible values are:
Normal: The animation plays forward as normal. After each animation cycle, the animation resets to the beginning state and starts over again. Default value.
Reverse: Plays the animation in reverse, starting from the end state. After each animation cycle, the animation resets to the end state and starts over again.
Alternate: The animation alternates between normal and reverse directions. In reverse, the animation starts at the end state and plays backwards. The animation timing function is also reversed.
Alternate-reverse: The animation alternates between reverse and normal directions, starting in reverse for the first iteration.
Durationanimation-delayThe duration (integer) of the animation in milliseconds, such as 1000. Default to 0 (no animation, jumps to last frame). Easinganimation-timing-functionSets the easing function used to animate the @ keyframe animation. Valid values include "ease", "ease-in", "ease-in-out", "linear", "frames (integer)" etc. Defaults to "linear" .endDelayn / aThe number of milliseconds to delay after the end of an animation. This is useful when sequencing multiple animations based on the end time of another animation. Defaults to 0.fillanimation-fill-modeDefines how the animation should apply styles to its target when the animation isn't playing anymore. Defaults to "none". Possible values are:
None: The animation should not apply any styles to the target when it is not playing. Default value.
Forwards: The target element will retain the computed styles defined in the last key frame (ie: when key frame is at 100%) when the animation isn't playing.
Backwards: The target element will retain the computed styles defined in the first key frame (ie: when key frame is at 0%) when the animation isn't playing.
Both: The target element will retain the computed styles defined in both the first and last key frames when the animation isn't playing.
IterationStartn/aSets the point in the iteration the animation should start. The value should be a positive, floating point number. In an animation with 1 iteration, an iterationStart value of 0.5 starts the animation half way through. In an animation with 2 iterations, an iiterationStart value of 1.5 starts the animation half way through the 2nd iteration etc. Defaults to 0.0.iterationsanimation-iteration-countSets the number of times the animation should run before stopping. A value of Infinity means forever. Defaults to 1.
This is the keyframeOptions parameter I used in the above example:
one
two
three
four
five
six
Var boxref = document.getElementById ("box")
Boxref.animate (boxframes, {
Duration: 1000
Fill: 'forwards'
Easing: 'ease-in'
})
If we wanted to use the animation shorthand property to define the same options in CSS, it would look like this:
one
Animation: animatethebox 1s ease-in forwards
Control animation (play, pause, etc.)
Part of the advantage of using Animation API to create a Keyframe animation is that you can manipulate the results on demand, such as pausing, skipping, or hooking to an animation's event handler. The first step in doing all of this is to assign the animation to the variable when the animate () method is called:
Var myanimation = Element.animate (keyframes, keyframeOptions)
This creates a reference to the instance of the Animation object to allow us to manipulate the animation through various exposed properties and methods:
one
two
three
four
Var myanimation = Element.animate (/ *.. * /)
Myanimation.pause () / / immediately pause animation to control it manually
Myanimation.curentTime = 1000 / / jump to 1 second from start of animation
Myanimation.play () / / play animation
This is the original example of playback using a control after modification:
Note that in this example, I animate () immediately calls the target element, which causes the animation to run immediately. To prevent this, I pause () then calls the method. This is the common mode you use when you want to control the animation manually:
one
two
three
four
five
six
seven
Var boxanimation = boxref.animate (boxframes, {
Duration: 1000
Fill: 'both'
Easing: 'ease-in'
})
Boxanimation.pause ()
Animated object instance properties and methods
The properties, methods, and event handlers of the animated object instance are listed below, which are created when a reference is assigned to the animate () method, as described above:
Attribute
CurrentTime: Gets or sets the current time value of the animation in milliseconds.
Effect: Gets or sets the target effect of an animation. Support for this property is currently limited in all browsers.
Finished: A promise object that's resolved when the animation has completed. Support for this property is currently limited in all browsers.
Id: Gets or sets a string used to identify the animation.
PlaybackRate: Integer that gets or sets a playback rate of the animation. For example, 1=normal, 0 = pause, 2 = double,-1 = backwards etc.
PlayState: Read-only property that returns the current state of the animation: "idle", "pending", "running", "paused", or "finished".
Ready: A promise object that's resolved when the animation is ready to be played. Support for this property is currently limited in all browsers.
StartTime: Floating point number that gets or sets the current time (in milliseconds) of the animation.
Timeline: Gets or sets the current timeline of the animation. Defaults to the document timeline (document.timeline). Support for this property is currently limited in all browsers.
Method
Cancel (): Cancels the animation.
Finish (): Immediately completes an animation.
Pause (): Pauses an animation.
Play (): Plays an animation.
Reverse (): Reverses the current direction of the animation and plays it.
Event handler
Oncancel: Triggered when the animation is canceled, such as by calling the cancel () method.
Onfinish: Triggered when the animation is finished, such as by calling the finish () method.
Create a simple scrubber using Web Animation API
By manipulating the currentTime property, the following adds a simple eraser to the basic animation we see:
I created a HTML5 Range Slider to use as a scrubber. When the animation runs (automatically) for the first time, the currentTime property value of the animation is continuously transferred to the slider to synchronize the two. There is currently no "onprogress" event handler or anything like that (as far as I know) only runs code while the WAAPI animation is running, so I use it to monitor the progress of the animation. After the animation is over, I use the WAAPI event call to unnecessarily stop updating the slider. RequestAnimationFrame () onfinishcancelAnimationFrame ()
Whenever a user interacts with Ranger Slider, I update the WAAPI animation to synchronize with the slider:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
Scrubber.addEventListener ('mousedown', ()) = > {
Boxanimation.pause ()
UpdateScrubber ()
})
Scrubber.addEventListener ('mouseup', ()) = > {
Boxanimation.play ()
})
Scrubber.addEventListener ('input', ()) = > {
Boxanimation.currentTime = scrubber.value * animationlength
})
When the user presses the slider, I pause the animation and update the slider's value to synchronize with the animation's currentTime property. The reverse occurs when the user drags the slider-I synchronize the currentTime property to reflect the value of the slider, so the former depends on the latter. Finally, when the user hovers the mouse over the slider, I resume the automatic playback of the animation.
Animate multiple elements at a time
In the next example, I'll use WAAPI to demonstrate how to animate multiple elements at a time and perform actions after they are all over.
Note: at the time of this writing, native support for WAAPI promises is unstable, even in Chrome and FF. I had to use Web Animation Next Polyfill to make this feature run in the browser.
There's nothing too complicated here. Basically I loop through and call each letter in the animate () header and store each instance of the Animation object in an array. With this array, I can loop through a series of animations as needed. The finished property of each animation returns a Promise, which is parsed when the animation is finished playing, and I use Promise.all () to reset the entire animation when all the animation is finished playing.
Create an animation using the Animation () constructor
So far, I've only used the animate () object to create a WAAPI animation directly on an element that returns an instance of an Animation object. I'll be dereliction of duty, but not to mention you can use the Animation () constructor to do the same thing.
Note: at the time of this writing, Animation () native support is unstable even in Chrome and FF. I had to use Web Animation Next Polyfill to make this feature run in the browser.
With the warning, here is how to call the Animation () constructor:
one
Var myanimation = new Animation ([effect] [, timeline])
This function takes two parameters:
Effect: animation effects. At the time of this writing, only keyframeEffect supports this object.
Timeline: animation Timeline. At the time of writing, only document.timeline supports it.
Let's take a look at how to use a simple example:
This is the JavaScript code:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
Var boxref = document.getElementById ("box")
Var boxkeyFrames = new KeyframeEffect (
Boxref, / / element to animate
[
{transform: 'translateX (0) rotate (0deg)', background:'red'}, / / keyframe
{transform: 'translateX (90vw) rotate (180deg)', background:'blue'}
]
{duration: 2000, fill: 'forwards', iterations: 5} / / keyframe options
);
Var boxanimation = new Animation (boxkeyFrames, document.timeline)
Boxanimation.play ()
The new KeyframeEffect () object is an integrated object that contains all the settings for the animation in one location, from the target element to the Keyframe to be used to the Keyframe option.
This is the end of the content of "analyzing the power of CSS keyframes in JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.