


JavaScript-based animation using Anime.js, Part 3: Exploring values, timelines, and playback
Sep 03, 2023 am 09:01 AMIn the previous tutorial in the Anime.js series, you learned about the different types of parameters that control how different target elements animate. You also learned how to use function arguments to gradually change the delay or duration of an element.
In this tutorial, we'll take it a step further and learn how to specify the property value itself using regular numbers, function-based values, and keyframes. You'll also learn how to play animations in sequence using the timeline.
Specify attribute value
Anime.js allows you to specify the final value of an animatable property of a target element. The animation's initial or starting value is the property's default value. Any value specified in CSS can also be used as the starting value. There are several ways to specify the final value.
It can also be a unitless number. In this case, the property's original or default units will be used when calculating any property values. You can also specify the value as a string, but the string must contain at least one numeric value. Examples of string values ??are 10vh
, 80%
, and 9.125turn
.
You can also specify an attribute value relative to the current value instead of specifying an absolute value. For example, you could use =150px
as the value to set the final translateY
value to be larger than the current value of 150px
. Remember that only addition, multiplication, and subtraction can be used when specifying relative values.
When animating colors, you cannot use color names such as red, black, and blue to set the final color value of the animation. In this case, the color animation will not happen at all, and the changes will be instantaneous. The only way to animate colors is to specify the values ??as hexadecimal numbers or RGB and HSL values.
You may have noticed that we did not specify an initial value for the target element to animate it. Anime.js automatically determines initial values ??based on our CSS and the default values ??of these properties. However, you can use an array to specify an initial value for a property other than its default value. The first item in the array represents the initial value, and the second item represents the final value.
Instead of using the same final value for all target elements, you can use functions to set different values ??for different parameters. The process is similar to specifying function-based property parameters.
var uniqueTranslation = anime({ targets: '.square', translateY: function(el, i) { return 50 * (i + 1); }, autoplay: false }); var randomScaling = anime({ targets: '.square', scale: function(el, i) { return Math.random()*1.5 + i/10; }, autoplay: false }); var randomRotation = anime({ targets: '.square', rotate: function() { return anime.random(-180, 180); }, autoplay: false }); var randomRadius = anime({ targets: '.square', borderRadius: function(el) { return 20 + Math.random()*el.offsetWidth/4; }, autoplay: false }); var randomAll = anime({ targets: '.square', translateY: function(el, i) { return 50 + 50 * i; }, scale: function(el, i) { return Math.random()*1.5 + i/10; }, rotate: function() { return anime.random(-180, 180); }, borderRadius: function(el) { return Math.random()*el.offsetWidth/2; }, duration: function() { return anime.random(1500, 2400); }, delay: function() { return anime.random(0, 1000); }, autoplay: false });
For the translateY
attribute, we use the index of the element to set the translation value. Using 50 * (i 1)
will increase the translateY
value of each element by 50 pixels.
The scaling animation also uses the index of the element and the built-in Math.random()
function returns a floating point pseudo-random number less than 1. This way the element scales randomly, but the i/10
part of the attribute slightly increases the likelihood that the element that ends up has a larger size.
In the code for the rotation animation, we use the anime.random(a, b)
helper function to get a random integer between -180 and 180. This function helps assign random values ??to properties such as translateY
and rotate
. Using this function to assign random scale values ??will produce extreme results.
The border radius values ????of different elements are determined by calculating the width of the target element using the el
function parameter. Finally, the last part of the code also assigns random values ??to the duration
and delay
parameters.
You can see that the animation implemented in the last part is very random. There is no relationship between an element's different attribute values ??or its delay and duration values. In real life, it's more sensible to use values ??that add some sense of direction to the animation.
You can also use keyframes to animate different properties of the target element. Each keyframe contains an array of property objects. You can use this object to specify the property values ??for that part of the animation, duration
, delay
, and easing
. The following code creates a keyframe-based translation animation.
var keyframeTranslation = anime({ targets: '.square', translateY: [ { value: 100, duration: 500}, { value: 300, duration: 1000, delay: 1000}, { value: 40, duration: 500, delay: 1000} ], autoplay: false }); var keyframeAll = anime({ targets: '.square', translateY: [ { value: 100, duration: 500}, { value: 300, duration: 1000, delay: 1000}, { value: 40, duration: 500, delay: 1000} ], scale: [ { value: 1.1, duration: 500}, { value: 0.5, duration: 1000, delay: 1000}, { value: 1, duration: 500, delay: 1000} ], rotate: [ { value: 60, duration: 500}, { value: -60, duration: 1000, delay: 1000}, { value: 75, duration: 500, delay: 1000} ], borderRadius: [ { value: 10, duration: 500}, { value: 50, duration: 1000, delay: 1000}, { value: 25, duration: 500, delay: 1000} ], delay: function(el, i) { return 100*(i+1) }, autoplay: false });
You can also animate multiple properties at once by specifying different or the same values ??for all parameters. In the second case, the global delay
parameter applies an initial delay to all elements based on index. This delay is independent of the delay applied to each property within the keyframe.
創(chuàng)建和操作時(shí)間線
到目前為止,在本系列中,我們一直在使用 delay
參數(shù)以特定順序播放不同的動畫。要為此目的使用延遲,我們還需要知道前一個動畫的持續(xù)時(shí)間。
隨著動畫序列的復(fù)雜性不斷增加,維護(hù)正確的延遲值變得非常繁瑣。其中一個動畫的持續(xù)時(shí)間的任何變化都會迫使我們重新計(jì)算所有延遲值,以保持動畫的原始序列。
解決這個問題的一個更好的方法是使用時(shí)間軸來控制動畫序列。您必須使用 anime.timeline()
函數(shù)在 Anime.js 中創(chuàng)建時(shí)間線。您還可以將不同的參數(shù)作為對象傳遞給該函數(shù)。這些參數(shù)可以指定時(shí)間線播放的方向、循環(huán)次數(shù)以及 autoplay
參數(shù)來確定是否應(yīng)自動播放動畫。所有這些參數(shù)都已在本系列的參數(shù)教程中詳細(xì)討論。
您可以使用 add()
方法將不同的動畫添加到時(shí)間軸。添加到時(shí)間線的所有動畫將按照添加順序播放??梢灾付ń^對或相對偏移值來控制動畫的播放順序。
當(dāng)使用相對偏移值時(shí),當(dāng)前動畫的開始時(shí)間是相對于前一個動畫的時(shí)間確定的。相對偏移可以分為三種類型:
- +=offset:在這種情況下,當(dāng)前動畫會在上一個動畫結(jié)束后經(jīng)過 offset 毫秒后開始播放。
- -=offset:在這種情況下,當(dāng)前動畫在上一個動畫結(jié)束前 offset 毫秒開始播放。
- *=offset:在這種情況下,當(dāng)前動畫會在前一個動畫的動畫持續(xù)時(shí)間的 offset 倍后的毫秒數(shù)后開始播放。
以下代碼展示了如何創(chuàng)建基本時(shí)間線和具有相對偏移值的時(shí)間線。
var basicTimeline = anime.timeline({ direction: "alternate", loop: 2, autoplay: false }); basicTimeline.add({ targets: '.square', translateY: 200 }).add({ targets: '.red', translateY: 100 }).add({ targets: '.blue', translateY: 0 }); var offsetTimeline = anime.timeline({ direction: "alternate", loop: 2, autoplay: false }); offsetTimeline.add({ targets: '.square', translateY: 200 }).add({ targets: '.red', offset: '+=1000', translateY: 100 }).add({ targets: '.blue', offset: '*=2', translateY: 0 });
嘗試單擊上述演示中的偏移時(shí)間線按鈕。您將看到紅色方塊動畫結(jié)束和藍(lán)色方塊動畫開始之間有 2 秒的延遲。
我們沒有為紅方塊動畫指定 duration
。因此,使用默認(rèn)值 1000ms 或 1s 作為持續(xù)時(shí)間。藍(lán)色方形動畫的乘數(shù)偏移量使該值加倍,這會導(dǎo)致動畫延遲兩秒。
當(dāng)使用絕對偏移值時(shí),時(shí)間線的起始時(shí)間用作參考點(diǎn)。通過對時(shí)間線開頭發(fā)生的動畫使用較大的偏移值,可以反轉(zhuǎn)動畫的播放順序。
播放選項(xiàng)
Anime.js 有多種選項(xiàng)可以在任何給定點(diǎn)播放、暫停、重新啟動或搜索動畫或時(shí)間線。
play()
函數(shù)允許我們從當(dāng)前進(jìn)度開始播放動畫。 pause()
函數(shù)將在調(diào)用該函數(shù)時(shí)凍結(jié)動畫。 restart()
?函數(shù)從頭開始播放動畫,無論其當(dāng)前進(jìn)度如何。 seek(value)
函數(shù)可用于將動畫提前 value
毫秒數(shù)。
您應(yīng)該記住,play()
函數(shù)僅從暫停時(shí)恢復(fù)動畫。如果動畫已經(jīng)結(jié)束,則無法使用 play()
重播動畫。要重播動畫,您必須使用 restart()
函數(shù)。
var slowAnimation = anime({ targets: '.square', translateY: 250, borderRadius: 50, duration: 4000, easing: 'linear', autoplay: false }); document.querySelector('.play').onclick = slowAnimation.play; document.querySelector('.pause').onclick = slowAnimation.pause; document.querySelector('.restart').onclick = slowAnimation.restart; var seekInput = document.querySelector('.seek'); seekInput.oninput = function() { slowAnimation.seek(slowAnimation.duration * (seekInput.value / 100)); };
請注意,我們沒有使用 seekInput.value
來設(shè)置查找函數(shù)的值。這是因?yàn)榉秶斎氲淖畲笾狄言跇?biāo)記中設(shè)置為 100。直接使用輸入范圍的值將允許我們最多查找 100 毫秒。將范圍輸入值乘以動畫持續(xù)時(shí)間可確保我們可以在范圍滑塊上從頭到尾查找動畫。
最終想法
在本教程中,您學(xué)習(xí)了如何將不同的屬性值設(shè)置為數(shù)字、函數(shù)或關(guān)鍵幀的動畫。您還學(xué)習(xí)了如何在 Anime.js 中控制和操作時(shí)間線來控制動畫序列的播放順序。
如果您正在尋找其他資源來學(xué)習(xí)或在工作中使用,請查看我們在 Envato 市場中提供的資源。
如果您對本教程有任何疑問,請?jiān)谠u論中告訴我。
The above is the detailed content of JavaScript-based animation using Anime.js, Part 3: Exploring values, timelines, and playback. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience
