You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何缩小MUI indeterminate类型CircularProgress的蓝色显示区域?

调整MUI indeterminate CircularProgress的显示范围

问题描述

参考MUI官方指南制作类Facebook加载Spinner,当前实现采用两层CircularProgress:下层为灰色determinate变体(value=100)作为背景,上层为蓝色indeterminate变体实现动态加载效果。需求是缩小上层蓝色进度圈的显示区域,让更多灰色背景可见,但indeterminate变体无法通过修改value属性实现,询问是否需要修改SVG及具体操作方法。

当前实现代码:

import { Box, CircularProgress, circularProgressClasses } from '@mui/material';

function Spinner(props){
  return (
    <Box
      sx={{
        position: 'relative',
      }}
    >
      <CircularProgress
        {...props}
        variant="determinate"
        size={40}
        thickness={4}
        value={100}
        sx={{
          color: (theme) =>
          theme.palette.grey[theme.palette.mode === 'light' ? 200 : 800],
        }}
      />
      <CircularProgress
        {...props}
        variant="indeterminate"
        size={40}
        thickness={4}
        disableShrink
        sx={{
          color: (theme) => (theme.palette.mode === 'light' ? '#1a90ff' : '#308fe8'),
          verticalAlign: "middle",
          animationDuration: '550ms',
          position: 'absolute',
          left: 0,
          [`& .${circularProgressClasses.circle}`]: {
            strokeLinecap: 'round',
          },
        }}
      />
    </Box>
  );
}

解决方案:无需修改SVG,通过CSS控制stroke-dasharray和stroke-dashoffset

indeterminate变体的动画本质是通过stroke-dasharray(定义虚线的段长与间隔)和stroke-dashoffset(控制虚线偏移量)实现的,我们可以直接覆盖这两个属性来缩小蓝色进度圈的显示范围。

修改上层CircularProgress的sx样式,调整.circle类的相关属性:

<CircularProgress
  {...props}
  variant="indeterminate"
  size={40}
  thickness={4}
  disableShrink
  sx={{
    color: (theme) => (theme.palette.mode === 'light' ? '#1a90ff' : '#308fe8'),
    verticalAlign: "middle",
    animationDuration: '550ms',
    position: 'absolute',
    left: 0,
    [`& .${circularProgressClasses.circle}`]: {
      strokeLinecap: 'round',
      // 调整这两个属性控制显示范围,数值可按需微调
      strokeDasharray: '60, 200',
      strokeDashoffset: '0',
    },
  }}
/>

原理说明

  • strokeDasharray: '60, 200':表示虚线可见段长度为60,间隔段长度为200。以当前size=40、thickness=4为例,进度圈周长约为113,60的可见段会比默认值短,从而缩小显示区域。
  • 保持strokeDashoffset配合动画,确保加载流动效果正常。
  • 若需精准控制,可先计算进度圈周长:周长 = 2 * Math.PI * (size/2 - thickness/2),再将strokeDasharray的第一个值设为目标可见段长度,第二个值设为周长减去可见段长度即可。比如要显示1/4圈,就将可见段设为周长/4,间隔设为周长*3/4。

精准示例(1/4圈效果)

计算当前参数下的周长:

size=40,thickness=4 → 有效半径 = 40/2 - 4/2 = 18 → 周长 ≈ 2 * 3.14 * 18 ≈ 113.04
1/4周长 ≈ 28.26,间隔段长度 ≈ 113.04 - 28.26 = 84.78

对应样式:

[`& .${circularProgressClasses.circle}`]: {
  strokeLinecap: 'round',
  strokeDasharray: '28.26, 84.78',
  strokeDashoffset: '0',
}

内容的提问来源于stack exchange,提问作者SC K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:33:28