Table of Contents
Specify attribute value
创建和操作时间线
播放选项
最终想法
Home CMS Tutorial WordPress JavaScript-based animation using Anime.js, Part 3: Exploring values, timelines, and playback

JavaScript-based animation using Anime.js, Part 3: Exploring values, timelines, and playback

Sep 03, 2023 am 09:01 AM

使用 Anime.js 基于 JavaScript 的动画,第 3 部分:探索值、时间轴和播放

In 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
});
Copy after login

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
});
Copy after login

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.

创建和操作时间线

到目前为止,在本系列中,我们一直在使用 delay 参数以特定顺序播放不同的动画。要为此目的使用延迟,我们还需要知道前一个动画的持续时间。

随着动画序列的复杂性不断增加,维护正确的延迟值变得非常繁琐。其中一个动画的持续时间的任何变化都会迫使我们重新计算所有延迟值,以保持动画的原始序列。

解决这个问题的一个更好的方法是使用时间轴来控制动画序列。您必须使用 anime.timeline() 函数在 Anime.js 中创建时间线。您还可以将不同的参数作为对象传递给该函数。这些参数可以指定时间线播放的方向、循环次数以及 autoplay 参数来确定是否应自动播放动画。所有这些参数都已在本系列的参数教程中详细讨论。

您可以使用 add() 方法将不同的动画添加到时间轴。添加到时间线的所有动画将按照添加顺序播放。可以指定绝对或相对偏移值来控制动画的播放顺序。

当使用相对偏移值时,当前动画的开始时间是相对于前一个动画的时间确定的。相对偏移可以分为三种类型:

  • +=offset:在这种情况下,当前动画会在上一个动画结束后经过 offset 毫秒后开始播放。
  • -=offset:在这种情况下,当前动画在上一个动画结束前 offset 毫秒开始播放。
  • *=offset:在这种情况下,当前动画会在前一个动画的动画持续时间的 offset 倍后的毫秒数后开始播放。

以下代码展示了如何创建基本时间线和具有相对偏移值的时间线。

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
 });
Copy after login

尝试单击上述演示中的偏移时间线按钮。您将看到红色方块动画结束和蓝色方块动画开始之间有 2 秒的延迟。

我们没有为红方块动画指定 duration 。因此,使用默认值 1000ms 或 1s 作为持续时间。蓝色方形动画的乘数偏移量使该值加倍,这会导致动画延迟两秒。

当使用绝对偏移值时,时间线的起始时间用作参考点。通过对时间线开头发生的动画使用较大的偏移值,可以反转动画的播放顺序。

播放选项

Anime.js 有多种选项可以在任何给定点播放、暂停、重新启动或搜索动画或时间线。

play() 函数允许我们从当前进度开始播放动画。 pause() 函数将在调用该函数时冻结动画。 restart() 函数从头开始播放动画,无论其当前进度如何。 seek(value) 函数可用于将动画提前 value 毫秒数。

您应该记住,play() 函数仅从暂停时恢复动画。如果动画已经结束,则无法使用 play() 重播动画。要重播动画,您必须使用 restart() 函数。

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));
};
Copy after login

请注意,我们没有使用 seekInput.value 来设置查找函数的值。这是因为范围输入的最大值已在标记中设置为 100。直接使用输入范围的值将允许我们最多查找 100 毫秒。将范围输入值乘以动画持续时间可确保我们可以在范围滑块上从头到尾查找动画。

最终想法

在本教程中,您学习了如何将不同的属性值设置为数字、函数或关键帧的动画。您还学习了如何在 Anime.js 中控制和操作时间线来控制动画序列的播放顺序。

如果您正在寻找其他资源来学习或在工作中使用,请查看我们在 Envato 市场中提供的资源。

如果您对本教程有任何疑问,请在评论中告诉我。

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles