如何开发支持自定义圆弧段长度占比的Sass混合宏?
多层旋转圆弧动画实现方案
需求说明
- 目标效果:制作对应参考图的多层旋转圆弧动画
- 效果特征:
- 最内层为完整圆形
- 橙色圆弧长度为整圆周长的80%
- 其余外侧圆弧长度为整圆周长的40%
- 现有进度:已完成各圆弧的基础样式、旋转动画配置,仅需优化mixin以支持传入圆弧长度占比参数,无需手动硬编码尺寸
现有代码实现
页面结构
<div id="container"> <div id="sc1"></div> <div id="sc2"></div> <div id="sc3"></div> <div id="sc4"></div> <div id="sc5"></div> </div>
原始SCSS代码
$width: 240px; $height: 240px; #container { width: $width; height: $height; position: relative; } @mixin semi-circle($w, $bg, $rt) { box-sizing: border-box; position: absolute; top: 50%; left: calc(#{$width / 2} - #{$w / 2}); border: $width/30 solid $bg; border-top: 0; width: $w; transform: rotate($rt); height: $w/2; border-bottom-left-radius: $w; border-bottom-right-radius: $w; animation: rotate 1200ms ease-in-out 3; transform-origin: top center; } #sc1 { @include semi-circle($width/6, #ffdc00, 0deg); } #sc2 { @include semi-circle($width/(60/19), #fba421, 10deg); animation-delay: -200ms; } #sc3 { @include semi-circle($width/(15/7), #c43688, -20deg); animation-delay: -400ms; } #sc4 { @include semi-circle($width/(60/37), #793e79, 20deg); animation-delay: -600ms; } #sc5 { @include semi-circle($width/(30/23), #5c3190, 60deg); animation-delay: -700ms; } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
Mixin 优化方案
在原有mixin基础上新增$ratio入参,取值范围为0~1,代表圆弧长度占整圆周长的比例,默认值0.5与原有半圆行为兼容。优化后通过外层容器裁切、内层伪元素绘制完整半圆的方式,实现任意占比的圆弧长度控制:
// 优化后的mixin,新增圆弧占比入参 @mixin semi-circle($w, $bg, $rt, $ratio: 0.5) { box-sizing: border-box; position: absolute; top: 50%; // 根据占比计算裁切后的显示宽度,保证弧长匹配设定值 $clip-width: $w * 2 * $ratio; left: calc(#{$width / 2} - #{$clip-width / 2}); border: $width/30 solid transparent; border-top: 0; width: $clip-width; overflow: hidden; transform: rotate($rt); height: $w/2; transform-origin: top center; // 内层伪元素绘制完整半圆,通过外层裁切控制实际显示的弧长 &::after { content: ''; position: absolute; top: 0; left: 0; width: $w; height: $w; border: $width/30 solid transparent; border-bottom-color: $bg; border-bottom-left-radius: $w; border-bottom-right-radius: $w; } animation: rotate 1200ms ease-in-out 3; }
优化后的调用示例
// 最内层完整圆,占比1 #sc1 { @include semi-circle($width/6, #ffdc00, 0deg, 1); } // 橙色圆弧,占比80% #sc2 { @include semi-circle($width/(60/19), #fba421, 10deg, 0.8); animation-delay: -200ms; } // 其余外侧圆弧,占比40% #sc3 { @include semi-circle($width/(15/7), #c43688, -20deg, 0.4); animation-delay: -400ms; } #sc4 { @include semi-circle($width/(60/37), #793e79, 20deg, 0.4); animation-delay: -600ms; } #sc5 { @include semi-circle($width/(30/23), #5c3190, 60deg, 0.4); animation-delay: -700ms; }
内容的提问来源于stack exchange,提问作者Billybobbonnet
相关产品推荐
相关产品推荐

