الرئيسية / تعلّم / كيف أصنع مخطط دائري (Donut) بنسبة مئوية متحركة؟

كيف أصنع مخطط دائري (Donut) بنسبة مئوية متحركة؟

الحلقة التي تمتلئ حتى نسبة معينة تعرض التقدم أو النتيجة بنظرة واحدة. نستخدم دائرة SVG مع stroke-dasharray، ونحرّك الرقم بـ CSS فقط عبر @property.

الخطوات

  1. ارسم دائرتين في SVG: واحدة للخلفية وواحدة للتقدم، وأعطِ دائرة التقدم pathLength="100" لتصبح النسبة مباشرة.
  2. حدّد النسبة في متغير: style="--p: 75"، واجعل stroke-dasharray: var(--p) 100.
  3. حرّك الحلقة بـ @keyframes من stroke-dasharray: 0 100 إلى القيمة النهائية.
  4. سجّل المتغير --n بـ @property من نوع integer وحرّكه، ثم اعرضه بـ counter() داخل ::after. ويمكن استخدام counter(n, arabic-indic) لعرض الأرقام العربية الهندية.
  5. أضف role="img" و aria-label بالنسبة الكاملة على الحاوية. تقليل الحركة: اعرض الحلقة والرقم النهائيين مباشرة.

الكود

HTML

<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Donut Percentage</title>
<style>
  @property --n { syntax: "<integer>"; inherits: false; initial-value: 0; }
  body { min-height: 100vh; display: grid; place-items: center; margin: 0; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; }
  .donut { --p: 75; position: relative; inline-size: 180px; aspect-ratio: 1; }
  .donut svg { inline-size: 100%; block-size: 100%; transform: rotate(-90deg); }
  .track, .fill { fill: none; stroke-width: 12; }
  .track { stroke: #e6e6ef; }
  .fill { stroke: #6c5ce7; stroke-linecap: round; stroke-dasharray: var(--p) 100;
    animation: ring 1.2s cubic-bezier(.2,.8,.2,1) both; }
  .num { position: absolute; inset: 0; display: grid; place-items: center; font-size: 2rem; font-weight: 700;
    counter-reset: n var(--n); animation: count 1.2s cubic-bezier(.2,.8,.2,1) both; }
  .num::after { content: counter(n) "%"; }          /* use counter(n, arabic-indic) for ٧٥٪ style digits */
  @keyframes ring { from { stroke-dasharray: 0 100; } }
  @keyframes count { from { --n: 0; } to { --n: 75; } }
  @media (prefers-reduced-motion: reduce) {
    .fill, .num { animation: none; }
    .num { --n: 75; }
  }
</style>
<div class="donut" role="img" aria-label="النسبة 75 بالمئة">
  <svg viewBox="0 0 44 44" aria-hidden="true">
    <circle class="track" cx="22" cy="22" r="16"/>
    <circle class="fill" cx="22" cy="22" r="16" pathLength="100"/>
  </svg>
  <span class="num" aria-hidden="true"></span>
</div>
</html>

تصنيفات مرتبطة: حركات الأرقام والعدادات · الرسوم البيانية والإنفوجرافيك