我们常用CSS 动画实现一些旋转、变大、变小、滑入、滑出,下面的代码用CSS 动画可以实现曲线运动,常见的应用场景,比如:添加商品飞入购物车,奥特曼盲盒C端召唤光点等。
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css曲线动画</title>
<style>
body{
margin: 0;
padding: 0;
}
.box{
position:absolute;
left: 0;
top: 0;
width: 0px;
height: 0px;
/* 一段曲线动画 */
/* animation: first-x 2s 1s 1 linear, first-y 2s 1s 1 ease-out; */
/* 两段曲线动画 */
animation: first-x 1s 1s 1 linear, first-y 1s 1s 1 ease-out,
sec-x 1s 3s 1 linear,
sec-y 1s 3s 1 cubic-bezier(0.66, 0.1, 1, 0.41);
animation-fill-mode: forwards;
}
.box-inner{
width: 50px;
height: 50px;
background: red;
position:absolute;
}
.relative{
position: relative;
width: 200px;
height: 200px;
background: pink;
}
/* 第一段y轴 */
@keyframes first-y {
0% {
top: 0px;
}
100% {
top: 200px;
}
}
/* 第一段x轴 */
@keyframes first-x {
0% {
left: 0;
}
100% {
left: 200px;
}
}
/* 第二段y轴 */
@keyframes sec-y {
0% {
top: 200px;
}
100% {
top: 600px;
}
}
/* 第二段x轴 */
@keyframes sec-x {
0% {
left: 200px;
transform: scale(1);
}
100% {
left: 400px;
transform: scale(0.5);
}
}
</style>
</head>
<body>
<div class='relative'>
<div class='box'>
<div class='box-inner'></div>
</div>
</div>
</body>
</html>
贝塞尔曲线
常用到的贝塞尔曲线如下图:
也可以自定义,贝塞尔曲线在线地址: https://cubic-bezier.com/
注意事项
如果要对一张长宽比较大的图片实现曲线运动,我们可以先把它包裹在一个长宽为0的div里,再把动画加到这个div上即可。这样可以简化定位距离的计算。