كيف أرسم جسيمات متحركة بـ Canvas؟
الجسيمات نقاط صغيرة كثيرة تتحرك معاً لتعطي إحساس الحياة في الخلفيات والعناوين. سنرسم مجموعة نقاط على عنصر canvas ونحركها بحلقة requestAnimationFrame واحدة.
الخطوات
- أنشئ عنصر canvas واضبط حجمه حسب devicePixelRatio ليبقى الرسم حاداً على الشاشات عالية الكثافة.
- أنشئ مصفوفة جسيمات، لكل جسيم موضع (x, y) وسرعة (vx, vy) ونصف قطر.
- في كل إطار: امسح اللوحة، حدّث المواضع، أعد الجسيم من الجهة المقابلة إذا خرج من الحافة، ثم ارسمه.
- أوقف الحلقة عندما تكون الصفحة مخفية (visibilitychange)، وأعد ضبط الحجم عند تغيير حجم النافذة.
- عند تفضيل تقليل الحركة ارسم إطاراً ثابتاً فقط. اجعل الـ canvas زخرفياً بـ aria-hidden="true" واكتب أي نص عربي في HTML فوقه، لا داخل الـ canvas.
الكود
HTML
<!doctype html>
<html lang="ar" dir="rtl">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Canvas Particles</title>
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0f1020; color: #fff; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; }
canvas { position: fixed; inset: 0; inline-size: 100%; block-size: 100%; }
h1 { position: relative; margin: 0; }
</style>
<canvas id="c" aria-hidden="true"></canvas>
<h1>تحريك كيت</h1>
<script>
const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
const reduce = matchMedia("(prefers-reduced-motion: reduce)");
let w = 0, h = 0, raf = 0, parts = [];
function resize() {
const dpr = window.devicePixelRatio || 1;
w = innerWidth; h = innerHeight;
canvas.width = w * dpr; canvas.height = h * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const count = Math.min(120, Math.round((w * h) / 12000));
parts = Array.from({ length: count }, () => ({
x: Math.random() * w, y: Math.random() * h,
vx: (Math.random() - .5) * .6, vy: (Math.random() - .5) * .6,
r: 1 + Math.random() * 2
}));
if (reduce.matches) frame(false);
}
function frame(move = true) {
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "rgba(160,150,255,.85)";
for (const p of parts) {
if (move) {
p.x = (p.x + p.vx + w) % w;
p.y = (p.y + p.vy + h) % h;
}
ctx.beginPath();
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
ctx.fill();
}
}
function loop() { frame(); raf = requestAnimationFrame(loop); }
function start() { cancelAnimationFrame(raf); if (!reduce.matches && !document.hidden) loop(); }
addEventListener("resize", () => { resize(); start(); });
document.addEventListener("visibilitychange", () => (document.hidden ? cancelAnimationFrame(raf) : start()));
reduce.addEventListener("change", () => { resize(); start(); });
resize(); start();
</script>
</html>