大厂前端工程师教你如何使用css3绘制任意角度扇形+动画

这里只是做下原理解释,原理:使用两个半圆做角度拼接。比如想绘制一个缺口朝右,缺口弧度30度角的扇形

资源网站搜索大全https://55wd.com

那么将由一个旋转65度角的半圆A+一个旋转-65度角的半圆B组合而成。代码:

<style>
.outer{
position: absolute;
 200px;
height: 200px;
transform: rotate(65deg);
clip: rect(0px,100px,200px,0px);/* 这个clip属性用来绘制半圆,在clip的rect范围内的内容显示出来,使用clip属性,元素必须是absolute的 */
border-radius: 100px;
background-color: yellow;
/*-webkit-animation: an1 2s infinite linear;*/
}
.pie{
position: absolute;
 200px;
height: 200px;
transform: rotate(-65deg);
clip: rect(0px,100px,200px,0px);
border-radius: 100px;
background-color: yellow;
/*-webkit-animation: an2 2s infinite linear;*/
}
</style>

<div></div>
<div></div>

这样可以绘制0-360任意角度的扇形了。然后,我们要绘制一个会动的扇形,比如这个缺口一开一合,向贪吃蛇一样。css3提供了animation属性,本文只考虑chrome,因此只加了-webkit-animation,需要兼容的同学另行处理。

解开上面两个css中注释掉的部分:-webkit-animation,然后增加如下css:

/**动画*/
@-webkit-keyframes an1{
       0% {transform: rotate(0deg);}
       50%{transform: rotate(90deg);}
       100%{transform: rotate(0deg);}
}
@-webkit-keyframes an2{
       0% {transform: rotate(0deg);}
       50%{transform: rotate(-90deg);}
       100%{transform: rotate(0deg);}
}

这样让A半圆在2秒内从0旋转到90在旋转到0,让B半圆在2秒内从0旋转到-90在旋转到0,刚好完成一次开闭的动作。

上面的半圆是通过clip产生的,假设我的场景是这个扇形的位置是变化的,比如贪吃蛇的场景,那么使用clip就不合适了。下面采取另外一种方法

<style>
.outer{
position: absolute;
 100px;
height: 200px;
border-radius: 100px 0 0 100px; /* 绘制半圆,采用只绘制左上角,左下角的方法,因此需要将宽度设置为高度的一半*/
transform: rotate(0deg);
transform-origin: 100% 50%;/* 这个很重要,需要设置旋转中心,默认旋转中心是元素的中间,但是我们绘制的是半圆,因此旋转中心应该是 100%宽度,50%高度*/
background-color: yellow;
-webkit-animation: an1 1s infinite linear;
}

.pie{
position: absolute;
 100px;
height: 200px;
transform: rotate(0deg);
transform-origin: 100% 50%;
border-radius: 100px 0 0 100px;
background-color: yellow;
-webkit-animation: an2 1s infinite linear;
}


/**动画*/
@-webkit-keyframes an1{
       0% {transform: rotate(0deg);}
       50%{transform: rotate(90deg);}
       100%{transform: rotate(0deg);}
}


@-webkit-keyframes an2{
       0% {transform: rotate(0deg);}
       50%{transform: rotate(-90deg);}
       100%{transform: rotate(0deg);}
}


.ct{
position: absolute;
 200px;
height: 200px;
}


</style>

<div class="ct" id="ctx">
  <div class="outer"></div>
  <div class="pie"></div> 
 </div>

<script type="text/javascript">
 
 var left = 0;
 var ctx = document.getElementById("ctx");


 setInterval(function () {
  left+=10;
  if(left>400){
  left=0;
  }
  ctx.style.left=left+"px";
 },1000);
</script>

效果可以看到,一个会动的圆形在往右边一动,缺口一开一合。

原文地址:https://www.cnblogs.com/ypppt/p/13229196.html