HTML - Canvas الرسوميات

HTML - عنصر <canvas> للرسم والرسوميات

عنصر <canvas> يُستخدم في HTML5 لإنشاء منطقة رسومية يمكن الرسم عليها باستخدام JavaScript. يتم استخدامه في تطبيقات مثل الرسوم التفاعلية، الألعاب، المخططات، والتصميمات الديناميكية.

🧱 الشكل الأساسي لعنصر canvas


<canvas id="myCanvas" width="300" height="150">
  المتصفح لا يدعم عنصر canvas.
</canvas>

🔹 الرسومات لا تظهر إلا بعد التعامل مع العنصر باستخدام JavaScript.

🧪 مثال: رسم مستطيل بسيط


<canvas id="myCanvas" width="300" height="150"></canvas>

<script>
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "#009578";
  ctx.fillRect(50, 30, 200, 100);
</script>

🖌️ أهم دوال الرسم في canvas

  • fillRect(x, y, width, height): لرسم مستطيل ملون.
  • strokeRect(x, y, width, height): لرسم مستطيل بإطار فقط.
  • clearRect(x, y, width, height): لمسح منطقة معينة.
  • beginPath(): لبدء رسم شكل جديد.
  • moveTo(x, y): لنقل المؤشر لمكان معين.
  • lineTo(x, y): لرسم خط من المكان الحالي إلى نقطة معينة.
  • arc(x, y, radius, startAngle, endAngle): لرسم دائرة أو قوس.
  • fill() و stroke(): لتلوين الشكل أو تحديد حدوده.

🖼️ مثال: رسم دائرة


<canvas id="circleCanvas" width="200" height="200"></canvas>

<script>
  const c = document.getElementById("circleCanvas");
  const ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(100, 100, 50, 0, 2 * Math.PI);
  ctx.fillStyle = "orange";
  ctx.fill();
  ctx.stroke();
</script>

📌 ملاحظات مهمة

  • عنصر <canvas> لا يدعم الرسم بنفسه، بل يتم عبر JavaScript فقط.
  • يُفضّل تحديد width و height داخل الوسم نفسه لتفادي التشويش.
  • يمكن استخدام مكتبات مثل Chart.js أو Fabric.js لتسهيل الرسم.

تعليقات

المشاركات الشائعة من هذه المدونة

C# - Arrays

Entity Framework - ما هو ORM؟ ونبذة عن Dapper وNHibernate

Entity Framework - مقدمة عن Entity Framework