مؤشر ساعة Canvas
- الصفحة السابقة رقم الساعة
- الصفحة التالية بدء الساعة
الجزء الرابع - رسم مؤشرات الساعة
الساعة تحتاج إلى مؤشرات. أنشئ دالة JavaScript لرسم مؤشرات الساعة:
JavaScript:
function drawClock() { drawFace(ctx, radius); drawNumbers(ctx, radius); drawTime(ctx, radius); } function drawTime(ctx, radius) { const now = new Date(); let hour = now.getHours(); let minute = now.getMinutes(); let second = now.getSeconds(); // الساعة hour = hour%12; hour = (hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60)); drawHand(ctx, hour, radius*0.5, radius*0.07); // الدقائق minute = (minute*Math.PI/30)+(second*Math.PI/(30*60)); drawHand(ctx, minute, radius*0.8, radius*0.07); // الثواني second = (second*Math.PI/30); drawHand(ctx, second, radius*0.9, radius*0.02); } function drawHand(ctx, pos, length, width) { ctx.beginPath(); ctx.lineWidth = width; ctx.lineCap = "round"; ctx.moveTo(0,0); ctx.rotate(pos); ctx.lineTo(0, -length); ctx.stroke(); ctx.rotate(-pos); }
شرح الكود
إنشاء جسم Date للحصول على الساعة والدقيقة والثانية:
const now = new Date(); let hour = now.getHours(); let minute = now.getMinutes(); let second = now.getSeconds();
حساب زاوية الساعة، ورسم طولها (نصف القطر) وعرضها (7% من القطر):
hour = hour%12; hour = (hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60)); drawHand(ctx, hour, radius*0.5, radius*0.07);
يُستخدم نفس التقنية لرسم مؤشر الساعة والمؤشر الثواني.
drawHand() عملية لا تحتاج إلى شرح. إنه يرسم خطًا بطول وعرض محدد.
يرجى الرجوع أيضًا إلى:
- الصفحة السابقة رقم الساعة
- الصفحة التالية بدء الساعة