الرئيسية / تعلّم / كيف تبني خلفية نجوم أو شبكة نقاط متصلة بـ Canvas؟

كيف تبني خلفية نجوم أو شبكة نقاط متصلة بـ Canvas؟

نقاط صغيرة تتحرك وتتصل بخطوط حين تقترب من بعضها هي خلفية مألوفة في صفحات التقنية. نبنيها على مقالة الجسيمات: نضيف رسم الخطوط حسب المسافة، ونوقف الحركة خارج الشاشة، ونضبط الدقة للشاشات الحادة.

الخطوات

  1. اضبط حجم الـ canvas الحقيقي على عرض العنصر × window.devicePixelRatio، ثم استدعِ ctx.setTransform(dpr, 0, 0, dpr, 0, 0) لتبقى الإحداثيات بوحدات CSS وتبقى الصورة حادة.
  2. أنشئ مصفوفة نقاط بمواقع وسرعات عشوائية، وحدّد عددها بحسب مساحة الخلفية وبحد أقصى.
  3. في كل إطار حرّك النقاط وارسمها، ثم لكل زوج أقرب من مسافة LINK ارسم خطا شفافيته تقل كلما بعدت النقطتان.
  4. استخدم requestAnimationFrame، وأوقف الحلقة عندما يخرج الـ canvas من الشاشة (IntersectionObserver) أو تُخفى التبويبة (visibilitychange).
  5. عند prefers-reduced-motion ارسم إطارا واحدا ثابتا فقط، واجعل الـ canvas aria-hidden.

المصادر

الكود

HTML

<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  body { margin: 0; background: #020617; color: #fff; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; }
  .hero { position: relative; height: 100vh; }
  canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
  h1 { position: relative; margin: 0; height: 100%; display: grid; place-items: center; font-size: clamp(1.8rem, 6vw, 3.5rem); pointer-events: none; }
</style>
<section class="hero">
  <canvas id="c" aria-hidden="true"></canvas>
  <h1>شبكة من النقاط المتصلة</h1>
</section>
<script>
  const canvas = document.getElementById('c'), ctx = canvas.getContext('2d');
  const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
  let w, h, dpr, pts = [], raf = 0, visible = true;
  const LINK = 120;                                              // max distance (CSS px) to draw a line
  function resize() {
    dpr = window.devicePixelRatio || 1;
    w = canvas.clientWidth; h = canvas.clientHeight;
    canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);   // sharp on HiDPI screens
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    const n = Math.min(90, Math.round(w * h / 14000));
    pts = Array.from({ length: n }, () => ({ x: Math.random() * w, y: Math.random() * h, vx: (Math.random() - .5) * .5, vy: (Math.random() - .5) * .5 }));
  }
  function draw() {
    ctx.clearRect(0, 0, w, h);
    for (const p of pts) {
      p.x += p.vx; p.y += p.vy;
      if (p.x < 0 || p.x > w) p.vx *= -1;
      if (p.y < 0 || p.y > h) p.vy *= -1;
    }
    for (let i = 0; i < pts.length; i++) {
      const a = pts[i];
      ctx.fillStyle = '#7dd3fc'; ctx.beginPath(); ctx.arc(a.x, a.y, 1.8, 0, Math.PI * 2); ctx.fill();
      for (let j = i + 1; j < pts.length; j++) {
        const b = pts[j], d = Math.hypot(a.x - b.x, a.y - b.y);
        if (d < LINK) { ctx.strokeStyle = `rgba(125,211,252,${1 - d / LINK})`; ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); }
      }
    }
  }
  function loop() { draw(); raf = requestAnimationFrame(loop); }
  function start() { if (!raf && visible && !reduce && !document.hidden) loop(); }
  function stop() { cancelAnimationFrame(raf); raf = 0; }
  resize(); draw();                                               // one still frame is the reduced-motion result
  addEventListener('resize', () => { resize(); draw(); });
  new IntersectionObserver(([e]) => { visible = e.isIntersecting; visible ? start() : stop(); }).observe(canvas);   // pause when off-screen
  document.addEventListener('visibilitychange', () => document.hidden ? stop() : start());
  start();
</script>
</html>

لم تجد الحركة التي تريدها؟ اطلبها من هنا

مقالات ذات صلة: