ارسم على اللوحة
القسم 9: Canvas: الرسم والألعابالدرس 9.1 · ⏱ 10 دقائق
<canvas> لوحة رسم. نرسم عليها بالكود: نختار اللون بـ fillStyle، ثم نرسم مستطيلًا بـ fillRect(x, y, عرض, ارتفاع) أو دائرة بـ arc.
📌 لاحظ
النقطة (0, 0) في الركن العلوي الأيسر، و y يكبر كلما نزلنا.
HTML
<canvas id="c" width="300" height="200"></canvas>
CSS
canvas { border: 1px solid #ccc; border-radius: 12px; }
JavaScript
const ctx = document.getElementById("c").getContext("2d");
// sky and grass
ctx.fillStyle = "#bfe6ff";
ctx.fillRect(0, 0, 300, 200);
ctx.fillStyle = "#6cc26c";
ctx.fillRect(0, 150, 300, 50);
// sun
ctx.fillStyle = "gold";
ctx.beginPath();
ctx.arc(250, 45, 25, 0, Math.PI * 2);
ctx.fill();
// house
ctx.fillStyle = "#e9a15a";
ctx.fillRect(80, 90, 100, 60);
ctx.fillStyle = "#c0392b";
ctx.beginPath();
ctx.moveTo(70, 90);
ctx.lineTo(130, 45);
ctx.lineTo(190, 90);
ctx.closePath();
ctx.fill();
// door
ctx.fillStyle = "#6b3e1f";
ctx.fillRect(118, 115, 24, 35);
🖥️ الصفحة في روبو ويب:

- أضف نافذتين للبيت.
- ارسم شجرة: جذع بني ودائرة خضراء.
📌 مثال آخر: علم بثلاثة ألوان
ثلاثة مستطيلات فوق بعض: أحمر وأبيض وأسود.
HTML
<canvas id="c" width="300" height="200"></canvas>
CSS
canvas { border: 1px solid #ccc; border-radius: 12px; }
JavaScript
const ctx = document.getElementById("c").getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 300, 66);
ctx.fillStyle = "white";
ctx.fillRect(0, 66, 300, 67);
ctx.fillStyle = "black";
ctx.fillRect(0, 133, 300, 67);
🖥️ الصفحة في روبو ويب:

✍️ طبّق بنفسك
جرّب المثال هنا: انسخ الكود إلى تبويباته، وغيّر فيه، وشاهد الصفحة تتغيّر.
✍️ طبّق هنا في الدرس✖ أغلق المعملأو افتح المعمل في صفحة جديدة ↗
🎯 تحدَّ نفسك
سهل
مربع أزرق في وسط اللوحة.
👀 اعرض الحل🙈 أخفِ الحل
HTML
<canvas id="c" width="300" height="200"></canvas>
CSS
canvas { border: 1px solid #ccc; border-radius: 12px; }
JavaScript
const ctx = document.getElementById("c").getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(100, 50, 100, 100);
🖥️ الصفحة في روبو ويب:

النتيجة: مربع أزرق.
متوسط
ثلاث دوائر بألوان إشارة المرور.
👀 اعرض الحل🙈 أخفِ الحل
HTML
<canvas id="c" width="300" height="200"></canvas>
CSS
canvas { border: 1px solid #ccc; border-radius: 12px; }
canvas { background: #333; }
JavaScript
const ctx = document.getElementById("c").getContext("2d");
const colors = ["red", "orange", "lime"];
for (let i = 0; i < 3; i++) {
ctx.fillStyle = colors[i];
ctx.beginPath();
ctx.arc(60 + i * 90, 100, 35, 0, Math.PI * 2);
ctx.fill();
}
🖥️ الصفحة في روبو ويب:

النتيجة: أحمر وبرتقالي وأخضر.
صعب
خط متعرّج من 5 قمم (lineTo داخل for).
👀 اعرض الحل🙈 أخفِ الحل
HTML
<canvas id="c" width="300" height="200"></canvas>
CSS
canvas { border: 1px solid #ccc; border-radius: 12px; }
JavaScript
const ctx = document.getElementById("c").getContext("2d");
ctx.strokeStyle = "purple";
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(0, 150);
for (let i = 0; i < 5; i++) {
ctx.lineTo(30 + i * 60, 50);
ctx.lineTo(60 + i * 60, 150);
}
ctx.stroke();
🖥️ الصفحة في روبو ويب:

النتيجة: خط بنفسجي متعرّج.

