如何使用Anime.js创建时间轴动画
Anime.js 是一个轻量级的 JavaScript 库,具有简单而强大的 API。它可与 DOM 元素、CSS 和 JavaScript 对象一起使用。
先决条件:
安装 Anime.js: 有两种方法可以在项目中使用 Anime.js:
- 您可以下载 anime.min.js 文件并直接使用它。
- 只需在 script 标签中搜索 anime.js CDN,并将其添加到您的项目中,如下所示:
<script src=”https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js”></script>
Anime.js 中使用的基本属性:
- targets: 用于定位和标识要应用动画的 CSS 选择器。
- duration: 动画持续的时间,以毫秒为单位。
- delay: 动画开始后的延迟时间,以毫秒为单位。
- translateX: 将元素定位于指定的 x 坐标。
- translateY: 将元素定位于指定的 Y 坐标。
- offset: 在不同动画之间设置延迟,例如在前一个动画之后的 x 秒后开始另一个动画。
创建应用程序和项目结构: 这是一个简单的网页。我们需要做的只是创建一个项目,并在其中创建一个名为 index.html 的 HTML 文件。
mkdir animation && cd animation
touch index.html
示例1:
index.html
HTML
<!DOCTYPE html>
<html>
<head>
<title>A nice example for timeline</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js">
</script>
<style>
html{
min-height: 200vh;
}
.ball {
width: 60px;
height: 60px;
margin-top: 120px;
margin-left:200px;
border-radius: 50%;
background-color: pink;
float: left;
}
</style>
</head>
<body>
<body>
<div class="ball first"></div>
<div class="ball second"></div>
<div class="ball third"></div>
<script>
let animation = anime.timeline({
duration: 500,
easing: 'easeInOutSine',
direction: 'alternate',
autoplay:false,
loop: true
});
animation.add({
targets: '.first',
translateY: -50,
backgroundColor: 'rgb(255, 0, 0)'
}).add({
targets: '.second',
translateY: -50,
backgroundColor: 'rgb(0, 255, 0)'
}).add({
targets: '.third',
translateY: -50,
backgroundColor: 'rgb(0, 0, 255)'
});
window.onscroll=()=>{
animation.play();
}
</script>
</body>
</html>
输出: 单击 index.html 在浏览器中打开它:
示例2: 在这个示例中,translateX属性变得更加清晰。它首先沿着负x轴进行平移,然后沿着正x轴进行平移。
index.html
HTML
<!DOCTYPE html>
<html>
<head>
<title>A nice example for timeline</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js">
</script>
<style>
html{
min-height:200vh;
}
.ball {
width: 200px;
height: 200px;
margin-top: 120px;
margin-left:200px;
background-color: pink;
float: left;
}
</style>
</head>
<body>
<body>
<div class="ball first"></div>
<div class="ball second"></div>
<div class="ball third"></div>
<script>
let animation = anime.timeline({
duration: 400,
easing: 'easeInOutSine',
direction: 'alternate',
autoplay:false,
loop: true
});
animation.add({
targets: '.first',
translateX: [-100,100],
backgroundColor: 'rgb(255, 0, 0)',
}).add({
targets: '.second',
translateX: [-100,100],
backgroundColor: 'rgb(0, 255, 0)',
}).add({
targets: '.third',
translateX: [-100,100],
backgroundColor: 'rgb(0, 0, 255)',
});
window.onscroll=()=>{
animation.play()
}
</script>
</body>
</html>
输出: 点击 index.html 文件以在浏览器中打开。