# 圆环进度加载（Circular progress ring）

- 俗称：圆形进度条；圆环加载百分比；环状上传进度；倒计时圆环
- 用在：按钮、卡片列表（工具和应用、个人网站、品牌官网）
- 触发：状态变化
- 感觉：利落、科技感
- 版本：1，更新于 2026-11-17

## 原理

给 SVG 进度圆环设好等于周长的 stroke-dasharray，再用 stroke-dashoffset 从满周长减到目标进度对应的值，由 CSS transition 按给定耗时和缓动平滑过渡；同时同步更新 role="progressbar" 的 aria-valuenow 与中心百分比文字；减少动态时关闭过渡直接跳到目标百分比。

适合：文件上传、任务同步、表单完成度、计时器与数据卡片，需要紧凑的百分比进度指示时。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 过渡时长 | 450ms | 150–1200ms |
| `easing` | 缓动 | cubic-bezier(0.22, 1, 0.36, 1) | — |

## 质量要求

- 开启"减少动态"时：关闭描边过渡动画，百分比更新时圆环和数字直接跳到新位置。
- 手机上：与桌面相同，SVG 按容器尺寸等比缩放，线宽在手机上保持清晰。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

## 提示词（可以直接交给 AI）

```text
请在我的项目里给按钮加上「圆环进度加载」（Circular progress ring）效果：给 SVG 进度圆环设好等于周长的 stroke-dasharray，再用 stroke-dashoffset 从满周长减到目标进度对应的值，由 CSS transition 按给定耗时和缓动平滑过渡；同时同步更新 role="progressbar" 的 aria-valuenow 与中心百分比文字；减少动态时关闭过渡直接跳到目标百分比。
参数：过渡时长 450ms，缓动 cubic-bezier(0.22, 1, 0.36, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/progress-ring.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<div class="cpr-ring" id="ring" role="progressbar" aria-label="上传进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
  <svg viewBox="0 0 96 96" aria-hidden="true">
    <circle class="cpr-track" cx="48" cy="48" r="40" />
    <circle class="cpr-fill" cx="48" cy="48" r="40" />
  </svg>
  <span class="cpr-value" data-cpr-value>0%</span>
</div>

<script type="module">
  import { progressRing } from './progress-ring.js';
  const ctl = progressRing(document.getElementById('ring'), { value: 0 });
  // 随真实上传或任务进度调用 ctl.set(percent)
  ctl.set(68);
</script>
```

CSS：

```css
/* 圆环进度加载（Circular progress ring）样式，配合 progress-ring.js。 */
.cpr-ring {
  position: relative;
  display: inline-grid;
  place-items: center;
  width: var(--cpr-size, 84px);
  height: var(--cpr-size, 84px);
}

.cpr-ring svg {
  width: 100%;
  height: 100%;
  transform: rotate(-90deg);
  overflow: visible;
}

.cpr-track,
.cpr-fill {
  fill: none;
  stroke-width: var(--cpr-stroke, 6);
}

.cpr-track {
  stroke: var(--cpr-track-color, color-mix(in srgb, currentColor 14%, transparent));
}

.cpr-fill {
  stroke: var(--cpr-color, currentColor);
  stroke-linecap: round;
  transition: stroke-dashoffset var(--cpr-duration, 450ms) var(--cpr-easing, cubic-bezier(0.22, 1, 0.36, 1));
}

.cpr-value {
  position: absolute;
  font-variant-numeric: tabular-nums;
  font-weight: 700;
  font-size: var(--cpr-font-size, 15px);
  line-height: 1;
}

.cpr-ring.cpr-reduced .cpr-fill {
  transition: none;
}

@media (prefers-reduced-motion: reduce) {
  .cpr-ring:not(.cpr-force) .cpr-fill {
    transition: none;
  }
}
```

JS（原生，不依赖任何库）：

```js
// 圆环进度加载（Circular progress ring）参考实现。
// 用法：容器内含 <svg><circle class="cpr-track"/><circle class="cpr-fill" r="40"/></svg>，可选 [data-cpr-value] 显示百分比。
// 调用 const ctl = progressRing(el, { duration: 450, easing: '...', value: 0 }); 后续调 ctl.set(75)，销毁调 ctl.destroy()。

const clamp = (n) => Math.min(100, Math.max(0, Number(n) || 0));

export function progressRing(el, {
  value = 0,
  duration = 450,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  format = (v) => `${Math.round(v)}%`,
  ignoreReducedMotion = false,
} = {}) {
  if (!(el instanceof Element)) return null;
  const fill = el.querySelector('.cpr-fill');
  if (!fill) return null;
  const r = Number(fill.getAttribute('r'));
  if (!Number.isFinite(r) || r <= 0) return null;
  const initial = value;

  const circ = 2 * Math.PI * r;
  const valueEl = el.querySelector('[data-cpr-value]');
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const prevRole = el.getAttribute('role');
  const prevMin = el.getAttribute('aria-valuemin');
  const prevMax = el.getAttribute('aria-valuemax');
  const prevNow = el.getAttribute('aria-valuenow');
  const prevText = valueEl ? valueEl.textContent : null;

  let current = clamp(initial);
  let destroyed = false;

  el.classList.add('cpr-ring');
  if (ignoreReducedMotion) el.classList.add('cpr-force');
  el.style.setProperty('--cpr-duration', `${Number(duration) || 450}ms`);
  el.style.setProperty('--cpr-easing', String(easing));
  if (!prevRole) el.setAttribute('role', 'progressbar');
  if (!prevMin) el.setAttribute('aria-valuemin', '0');
  if (!prevMax) el.setAttribute('aria-valuemax', '100');

  const apply = (val, immediate) => {
    if (destroyed) return;
    current = clamp(val);
    const offset = circ * (1 - current / 100);
    if (immediate) fill.style.transition = 'none';
    fill.style.strokeDasharray = `${circ}`;
    fill.style.strokeDashoffset = `${offset}`;
    el.setAttribute('aria-valuenow', String(Math.round(current)));
    if (valueEl) valueEl.textContent = format(current);
    if (immediate) {
      void fill.getBoundingClientRect();
      if (!(reduceQuery?.matches && !ignoreReducedMotion)) fill.style.transition = '';
    }
  };

  // 初始化位置不触发开场过渡
  apply(current, true);

  return {
    set(next) {
      if (destroyed) return;
      const skipAnim = Boolean(reduceQuery?.matches && !ignoreReducedMotion);
      apply(next, skipAnim);
      if (destroyed) return;
      el.dispatchEvent(new CustomEvent('progresschange', { bubbles: true, detail: { value: current } }));
    },
    value() {
      return current;
    },
    destroy() {
      if (destroyed) return;
      destroyed = true;
      el.classList.remove('cpr-force');
      el.style.removeProperty('--cpr-duration');
      el.style.removeProperty('--cpr-easing');
      fill.style.strokeDasharray = '';
      fill.style.strokeDashoffset = '';
      fill.style.transition = '';
      if (prevRole === null) el.removeAttribute('role'); else el.setAttribute('role', prevRole);
      if (prevMin === null) el.removeAttribute('aria-valuemin'); else el.setAttribute('aria-valuemin', prevMin);
      if (prevMax === null) el.removeAttribute('aria-valuemax'); else el.setAttribute('aria-valuemax', prevMax);
      if (prevNow === null) el.removeAttribute('aria-valuenow'); else el.setAttribute('aria-valuenow', prevNow);
      if (valueEl && prevText !== null) valueEl.textContent = prevText;
    },
  };
}
```

## 出处

- 本站自研：标准 SVG 圆环 stroke-dashoffset 过渡方案，配合 role="progressbar" 与 destroy 清理契约
