近日,同事在公司的技术分享上,分享了css动画相关知识,并演示了基本的动画效果,作为开发人员,要站在用户的角度进行考虑,一些效果不能够太突兀,需要有过渡,显得自然些。
下去后我也在电脑尝试各种动画效果,直到我看到了这个,css实现星球环绕效果,迫不及待试了试juejin.cn/post/698704…
我又在此基础上加入了box-shadow元素,看起来是挺炫酷的
transform
transform中有几个常用属性:translate
、scale
、rotate
。
首先,transform的坐标轴为横轴X,向右为正,纵轴为y,向下为正,竖轴为Z,屏幕里到屏幕外为z轴正方向。
translate
代表平移,参数分别为x轴偏移量,y轴偏移量、z轴偏移量,默认X轴偏移量,如
transform: translate(10px, 10px 10px)
scale
代表缩放,参数为缩放倍数,如
transform: scale(0.5)
rotate
代表旋转,参数为旋转角度,默认绕z轴旋转,顺时针旋转,如
transform: rotate(45deg);
动画
使用动画我们需要使用到@keyframes
和animaion
@keyframes
需要声明从0%到100%过程中的变化,如
@keyframes identifier {
0% {
transform: translate(0, 0, 0);
}
50% {
transform: tranlate(10px, 0, 0);
}
100% {
transform: tranalate(10px, 10px, 10px);
}
}
animaion
是使用上面的动画的,哪一个元素使用该动画,就将animaion
写到哪个元素上面。
animaion
基本用法是,分别代表动画名称、动画时间、过渡方式和动画运行次数。
animaion: name duration timing-function iteration-count
基本用到的就这么多,可以开干了。
实现双星环绕效果
1. 基本样式构建
<div class="content">
<div class="demo1">
<div class="ball ball1"></div>
<div class="ball ball2"></div>
</div>
</div>
* {
margin: 0;
padding: 0;
}
body, html {
width: 100%;
height: 100%;
background-color: #000;
}
.content {
width: 100%;
height: 100%;
}
.demo1 {
position: relative;
width: 800px;
height: 800px;
color: #fff;
cursor: pointer;
border: 2px solid #fff;
margin: 50px auto;
border-radius: 50%;
}
.demo1 .ball {
position: absolute;
width: 100px;
height: 100px;
border-radius: 50%;
}
.ball1 {
top: -50px;
left: 350px;
background-color: #0ff;
}
.ball2 {
top: 750px;
left: 350px;
background-color: #ffc;
}
2. 添加动画效果
.demo1 {
transform: scaleY(0.5);
animation: rorate-demo 20s linear infinite;
}
.ball {
transform: scaleY(2);
animation: rorate-ball 20s linear infinite;
}
@keyframes rorate-demo {
0% {
transform: rotate(-45deg) scaleY(0.5) rotate(0);
}
100% {
transform: rotate(-45deg) scaleY(0.5) rotate(360deg);
}
}
@keyframes rorate-ball {
0% {
transform: rotate(0) scaleY(2) rotate(45deg);
}
100% {
transform: rotate(-360deg) scaleY(2) rotate(45deg);
}
}
transform属性的执行顺序是从右向左
此动画的基本原理为demo盒子带着上面的小球ball一起转动,需要注意的是,使用scale
和rotate
,因为小球是在demo平面上,demo面进行收缩处理和旋转,小球会受影响,我们需要中和这种影响,即小球按照demo面的相反操作。
box-shadow
最后,我们加上box-shadow,大功告成了。
.ball1{
box-shadow: inset 0px 0px 50px #fff, inset 10px 0px 50px #f0f,
inset -10px 0px 50px #0ff, inset 10px 0px 50px #f0f,
inset -10px 0px 30px #0ff, 0px 0px 30px #fff, -10px 0px 50px #f0f,
10px 0px 50px #0ff;
}
.ball2{
box-shadow: inset 0px 0px 50px #fcc, inset 10px 0px 50px #fcc,
inset -10px 0px 50px #0ff, inset 10px 0px 50px #fcc,
inset -10px 0px 30px #0ff, 0px 0px 30px #fff, -10px 0px 50px #00f,
10px 0px 50px #0ff;
}
最终效果呈现