مرجع سريع

ورقة مساعدة لواجهة برمجة تطبيقات HTML5 2D Canvas

مرجع سريع لـ HTML5 2D Canvas: إنشاء السياق، الأشكال الأساسية، المسارات، التحويلات، رسم الصور، وحفظ الحالة.

· تاريخ النشر

دليل مرجعي سريع لواجهة برمجة سياق الرسم ثنائي الأبعاد في HTML5 Canvas (CanvasRenderingContext2D).

الحصول على سياق الرسم (Context)

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

الأشكال الأساسية وأنماط التعبئة

// أنماط الألوان والخطوط
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'

// رسم المستطيلات مباشرة: x, y, width, height
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);

المسارات والأشكال المخصصة (Paths)

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();

ctx.fill();
ctx.stroke();

الأقواس والدوائر

// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();

مكدس حفظ واستعادة الحالة (Save & Restore)

ctx.save();    // حفظ الحالة الحالية في المكدس
// تعديل نمط التعبئة والتحويلات والقص والظلال...
ctx.restore(); // استعادة الحالة السابقة من المكدس

تشمل الحالة المحفوظة: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation ومصفوفة التحويل الحالية.


تحويلات الإحداثيات (Transformations)

ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);

// الدوران حول نقطة أصل مخصصة (ox, oy)
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);

رسم الصور ومعالجتها

const img = new Image();
img.onload = () => {
  // رسم الصورة بالكامل عند الإحداثيات (x, y)
  ctx.drawImage(img, 0, 0);

  // رسم الصورة بقياس محدد: (img, dx, dy, dWidth, dHeight)
  ctx.drawImage(img, 0, 0, 150, 100);

  // اقتصاص جزء من الصورة ورسمه: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';

نمط حلقة الرسوم المتحركة (Animation Loop)

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // رسم عناصر الإطار الحالي...
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

موضوعات ذات صلة