小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
本文同时参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金
介绍
龙珠中经常出现的一个战斗效果是人物移动会出现残影,来表示速度很快,肉眼无法完全捕获。本期我们就用scss+gsap.js去实现这个效果。具体效果如下图所示:
感觉还有点意思吧,而且非常的简单,我们将会从基本结构,图层样式,残影事件来讲明,要开始咯~
正文
1.基础结构
我们本次用vite去搭建的项目,而且用了module模式,方便引入模块。
<div id="app">
<div class="hero">
<div class="hero-body"></div>
<div class="hero-body"></div>
<div class="hero-body"></div>
<div class="hero-body"></div>
<div class="hero-body"></div>
</div>
</div>
<script type="module" src="./app.js"></script>
复制代码
这里我们的html结构,div.hero里面将存在5个div.hero-body,相信大家就会猜到,其中一个是本体,其他的就是残影了,只是后面会用绝对定位让他们重叠在一起。因为较为简单故app.js里的结构和动画逻辑将在后面介绍。
2.图层样式
我们本次将使用scss去编写。
#app{
width: 100%;
height: 100vh;
position: relative;
background-color: black;
overflow: hidden;
}
.hero{
width: 280px;
height: 130px;
position: absolute;
.hero-body{
position: absolute;
left: calc(50vw - 140px);
top: calc(50vh - 65px);
width: 100%;
height: 100%;
background: url("./assets/hero.png") 0 0 no-repeat;
background-size: 100% auto;
@for $i from 1 through 5 {
&:nth-child(#{$i}) {
opacity:#{$i*0.2};
filter: drop-shadow(3px 3px #{4px*$i} rgba(252, 233, 124,.5));
}
}
}
}
复制代码
我们先让div#app占满屏幕,确定出div.hero的大小,然后将其下面的div.hero-body均变为同一张背景图,并让其初始位置为屏幕中央。然后我们用scss的for语法一次去遍历这五个图层,其遍历主要目的就是让他们的透明度由浅入深,因为其他一到四都是虚影,第五张图才是真正的身体。另外这次还用了drop-shadow给身体图片加了一层金光,也就是龙珠中气包裹全身效果。
下面我们先在控制台关掉绝对定位,每张图的变化效果会非常醒目:
3.残影事件
接下来,就是我们所有的逻辑代码,核心代码只有几行而已。
/*app.js*/
import "./style.scss"
import { gsap } from "gsap"
class Application {
constructor() {
this.init();
}
init(){
this.bindEvent();
}
bindEvent(){
window.addEventListener("mousemove", this.onMouseMove.bind(this))
}
onMouseMove(e) {
gsap.to(".hero-body", {
left: e.clientX - 140,
top: e.clientY - 65,
stagger: -0.02
});
}
}
window.onload = new Application();
复制代码
我们通过这几行代码一眼可以了解到。我们绑定鼠标移动事件,拿到坐标后用过gsap.to方法传给div.hero-body指定要改变的left和top属性。到这里刚才的悟空图片就可以根据你的鼠标去移动了。至于残影效果相信你即便没看gsap文档也会知道是哪句了,对就是stagger意思就是错开,可以设定好时间单位,让这些图层逐个错开形成残影效果。
结语
我们要讲的仅仅只有这些,使用了gsap.js后去实现是不是非常的简单,在线演示。
其实gsap在我们动画开发中极为常用,它还有很多方法让我们去发掘,更多的效果等着我们去创造,还等什么抓紧时间一起来挥舞这把js界动画的瑞士军刀吧~