最終的效果是:用純css實現動態畫圓的動畫效果
html結構如下:
<div class="wrap">
<div class="circle"></div>
<div class="top"></div>
<div class="bottom"></div>
</div>
實現的思路就是:
1. 首先定義外層容器大小,本例採用200x200,
.wrap{
position: relative;
width: 200px;
height: 200px;
overflow: hidden;
}
2. 通過border-radius畫一個圓環,這個比較簡單
.circle{
height: 100%;
box-sizing: border-box;
border: 20px solid red;
border-radius: 50%;
}
效果如下:
2. 然後用上下兩層擋板遮住這個圓環,通過旋轉擋板將圓環慢慢露出,過程如下圖所示:
通過將下層擋板旋轉180deg就能夠實現將下半圓慢慢畫出的效果,畫完以後就需要將其隱藏起來,那該如何實現呢?
這裏我用了opacity這個屬性,當100%時將其設置爲0,同時設置animation-fill-mode: forwards;這樣就隱藏了
0%{
transform: rotate( 0 );
}
99%{
transform: rotate( 180deg );
opacity: 1;
}
100%{
transform: rotate( 180deg );
opacity: 0;
}
3. 那如何顯示上半圓呢?同樣的思路我們對上面擋板進行旋轉,通過實際效果我們可以看到,雖然上半圓露出來了,但是確把下半圓給遮擋了。
如何解決這個問題呢?
我們可以在下半圓和擋板間再放一個半圓,同時設置他們的z-index,讓上面的擋板旋轉時被下半圓遮住,這樣就可以了。
說的有些複雜,相當於我們現在有四個元素:上擋板,下擋板,底部的大圓環,一個處在下擋板和大圓環間的半圓。
它們的z-index如下:
上擋板:1
下擋板和底部的大圓間的半圓:2
下擋板:3
爲了不增加額外的元素,下擋板和底部的大圓間的半圓我們通過僞元素來實現
.circle:before{
content: '';
position: absolute;
display: block;
width: 100%;
height: 50%;
box-sizing: border-box;
top: 50%;
left: 0;
border: 20px solid red;
border-top: transparent;
border-radius: 0 0 50% 50%/ 0 0 100% 100%;
z-index: 2;
}
4. 組後再結合css3的transform動畫就可以了,需要注意的是,上擋板和下擋板動畫是同時開始了,所以上擋板的動畫要設置一個延時,時長就是下擋板動畫的時長
本例用到的知識點如下:
1. 如何畫一個圓環
2. 如何畫一個半圓
3. css3動畫
4. 定位
最終代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>動態畫一個圓環</title>
<style>
*{
margin: 0; padding: 0;
}
.wrap{
position: relative;
width: 200px;
height: 200px;
overflow: hidden;
}
.circle{
height: 100%;
box-sizing: border-box;
border: 20px solid red;
border-radius: 50%;
}
.circle:before{
content: '';
position: absolute;
display: block;
width: 100%;
height: 50%;
box-sizing: border-box;
top: 50%;
left: 0;
border: 20px solid red;
border-top: transparent;
border-radius: 0 0 50% 50%/ 0 0 100% 100%;
z-index: 2;
}
.top, .bottom{
position: absolute;
left: 0px;
width: 100%;
height: 50%;
box-sizing: border-box;
background: white;
}
.top{
top: 0;
z-index: 1;
transform-origin: center bottom;
animation: 1s back-half linear 1s;
animation-fill-mode: forwards;
}
.bottom{
z-index: 3;
top: 50%;
transform-origin: center top;
animation: 1s front-half linear;
animation-fill-mode: forwards;
}
@keyframes front-half{
0%{
transform: rotate( 0 );
}
99%{
transform: rotate( 180deg );
opacity: 1;
}
100%{
transform: rotate( 180deg );
opacity: 0;
}
}
@keyframes back-half{
0%{
transform: rotate( 0 );
}
99%{
transform: rotate( 180deg );
opacity: 1;
}
100%{
transform: rotate( 180deg );
opacity: 0;
}
}
</style>
</head>
<body>
<div class="wrap">
<div class="circle"></div>
<div class="top"></div>
<div class="bottom"></div>
</div>
</body>
</html>