使用纯CSS进行径向擦拭; 如果不是SVG替代品

dan*_*Mad 4 html css svg css-transitions css-animations

我发现这个问题已得到解答,似乎可以用SVG实现径向擦除动画.

我希望实现border: 1px solid green;类似以下示例的效果:

在此输入图像描述

我想知道的是,如果纯CSS可以实现这一点,那将是理想的选择.

如果使用CSS无法实现,我将如何使用SVG解决这类问题?

Har*_*rry 8

CSS不适合像这样的动画.虽然您可以使用CSS,但最好是使用SVG.对于纯CSS版本,您可以尝试调整我的答案中提供的片段,但我不会真的推荐它,因为您可以看到它非常复杂.

您所要做的就是使用一个circle元素,将其设置为stroke-dasharray等于圆周,然后stroke-dashoffset在下面的代码片段中设置相似的动画.

stroke-dasharray属性为cirlce(边框)创建一个虚线笔划,其中每个笔划和它们之间的破折号将具有为属性指定的长度.

stroke-dashoffset属性指定圆圈笔划应开始的偏移量.当偏移量为at时0,绿色的笔划是可见的,而当偏移量处于314(等于周长)时,笔划之间的破折号变得可见.因此,它最终产生擦拭效果.

svg {
  height: 100px;
  width: 100px;
  transform: rotate(-90deg);
}
circle {
  stroke: green;
  fill: none;
  stroke-dasharray: 314; /* equal to circumference of circle 2 * 3.14 * 50 */
  animation: wipe 2s linear infinite;
}
@keyframes wipe {
  0% {
    stroke-dashoffset: 0;
  }
  30%, 50% {
    stroke-dashoffset: 314;
  }
  80%, 100% {
    stroke-dashoffset: 0;
  }  
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<svg viewBox='0 0 100 100'>
  <circle cx='50' cy='50' r='40' />
</svg>
Run Code Online (Sandbox Code Playgroud)


上面的示例使用无限动画,因此擦除和重绘将连续运行.如果必须打开/关闭它,那么最好transition在下面的代码段中使用.我已经完成了这项工作,:hover但您可以轻松地将其调整为点击或其他事件.

svg {
  height: 100px;
  width: 100px;
  transform: rotate(-90deg);
}
circle {
  stroke: green;
  fill: none;
  stroke-dasharray: 314; /* equal to circumference of circle 2 * 3.14 * 50 */
  stroke-dashoffset: 0; /* initial setting */
  transition: all 2s;
}
svg:hover circle{
  stroke-dashoffset: 314;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<svg viewBox='0 0 100 100'>
  <circle cx='50' cy='50' r='40' />
</svg>
Run Code Online (Sandbox Code Playgroud)