使用CSS动画实现 时钟转动效果
此案例主要运用到了css动画的功能。
先将外圆画好,时钟的时间轴先画正中间那一根,绝对定位到中间,然后复制时间轴类名,并依次添加旋转30度的css代码,需要注意的是,后面使用transform:rotate()会覆盖掉前面的transform:translate()属性,因此都要加上translate。然后画一个白色的遮罩层,放在外圆的正中间,以圆形挡住后面的大部分时间轴。接着开始画时、分、秒指针,依然是绝对定位到中间,但是指针的旋转点是自身中底部,因此transform属性设置为translate(-50%,-100%),指针整体上去,并设置旋转中心transform-origin:bottom,即可实现指针按顺时针方向旋转。
时钟的起点我定义为0秒,秒针转一圈是360°,因此动画代码为:
@keyframes rotate360 {
/* 起始点是0秒,此处可省略动画起点from */
to {
/* 避免translate被覆盖,此处可再添加translate */
transform: translate(-50%, -100%) rotate(360deg);
}
}
然后给秒针加上动画属性,速度曲线我这里设置的是steps(60),在60s动画里一共有60帧,那么相当于秒针一秒走一次,一分钟走完一圈。
animation: rotate360 60s steps(60) infinite;
给分针加上动画属性,这里的速度曲线建议使用linear,随着秒针的转动,分针慢慢过渡转动。
animation: rotate360 3600s linear infinite;
给时针加上动画属性,跟分针同理。
animation: rotate360 43200s linear infinite;
最后,加上一个小黑圆点放在正中间,时分秒针的旋转中心都在这小黑点上,让时钟看起来更完美一些。
CSS时钟动画,完整代码如下:
<style>
* {
margin: 0;
padding: 0;
}
.clock {
box-sizing: border-box;
border-radius: 50%;
border: 7px solid #000;
width: 500px;
height: 500px;
position: relative;
margin: 100px auto;
overflow: hidden;
}
.line {
position: absolute;
left: 50%;
width: 7px;
height: 500px;
background-color: gray;
transform: translate(-50%);
}
.line:nth-of-type(2) {
/* 六条线,各旋转30度 */
transform: translate(-50%) rotate(30deg);
}
.line:nth-of-type(3) {
transform: translate(-50%) rotate(60deg);
}
.line:nth-of-type(4) {
transform: translate(-50%) rotate(90deg);
}
.line:nth-of-type(5) {
transform: translate(-50%) rotate(120deg);
}
.line:nth-of-type(6) {
transform: translate(-50%) rotate(150deg);
}
.mark {
width: 370px;
height: 370px;
background-color: #fff;
border-radius: 50%;
/* 将遮罩层绝对垂直居中到父元素里 */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.hour,
.minute,
.second {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -100%);
/* 设置时、分、秒针的旋转中心为底部 */
transform-origin: bottom;
}
.hour {
width: 10px;
height: 90px;
background-color: rgb(73, 6, 6);
/* 给时针设置匀速转动的动画效果 */
animation: rotate360 43200s linear infinite;
}
.minute {
width: 7px;
height: 110px;
background-color: rgb(71, 248, 55);
/* 给分针设置匀速转动的动画效果 */
animation: rotate360 3600s linear infinite;
}
.second {
width: 4px;
height: 130px;
background-color: rgb(145, 132, 255);
/* 给秒针设置60帧动画效果,1秒1帧,60s转完一圈 */
animation: rotate360 60s steps(60) infinite;
}
.dot {
width: 22px;
height: 22px;
background-color: #000;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
@keyframes rotate360 {
/* 起始点是0秒(原样),此处可省略动画起点from */
to {
/* 避免translate被覆盖,此处可再添加translate */
transform: translate(-50%, -100%) rotate(360deg);
}
}
</style>
<div class="clock">
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<!-- 白色遮罩层 -->
<div class="mark"></div>
<!-- 时、分、针进行动画效果 -->
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
<!-- 时钟正中的小圆点 -->
<div class="dot"></div>
</div>