CSS | 使用 SVG 和 CSS 创建加载动画

1 概述

先看一下效果:
在这里插入图片描述

2 代码实现

2.1 HTML

<div class="svg-loader">
    <svg class="svg-container" height="100" width="100" viewBox="0 0 100 100">
        <circle class="loader-svg bg" cx="50" cy="50" r="45"></circle>
        <circle class="loader-svg animate" cx="50" cy="50" r="45"></circle>
    </svg>
</div>

从上面的演示中可以明显看出,动画由两个圆组成,一个在另一个上面,第一个圆比第二个圆厚,两个圆都有相同的圆周,给人一种旋转的错觉。

圆圈内的 cx 和 cy 属性分别是两个圆圈的 x 轴和 y 轴坐标。它们确保两个圆的中心在同一个坐标上。

2.2 CSS

.svg-loader{
  display:flex;
  position: relative;
  align-content: space-around;
  justify-content: center;
}
.loader-svg{
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  fill: none;
  stroke-width: 5px;
  stroke-linecap: round;
  stroke: rgb(64, 0, 148);
}
.loader-svg.bg{
  stroke-width: 8px;
  stroke: rgb(207, 205, 245);
}

上面的 css 确保元素在容器中居中,以及两个圆圈有不同的笔画宽度和颜色。

然后,我们为第二个圆圈作动画:

.animate{
  stroke-dasharray: 242.6;
  animation: fill-animation 1s cubic-bezier(1,1,1,1) 0s infinite;
}

@keyframes fill-animation{
  0%{
    stroke-dasharray: 40 242.6;
    stroke-dashoffset: 0;
  }
  50%{
    stroke-dasharray: 141.3;
    stroke-dashoffset: 141.3;
  }
  100%{
    stroke-dasharray: 40 242.6;
    stroke-dashoffset: 282.6;
  }
}

3 总结

实现动画的关键之处是使用了 animatestroke-dasharray 的属性,能帮助我们绘制间隙。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孟华328

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值