ساعة Canvas

في الفصول القادمة، سنستخدم لوحة HTML لبناء ساعة محاكاة.

الجزء الأول - إنشاء اللوحة

الساعة تحتاج إلى حاوية HTML. إنشاء لوحة HTML:

كود HTML:

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawClock();
function drawClock() {
  ctx.arc(0, 0, radius, 0 , 2 * Math.PI);
  ctx.fillStyle = "white";
  ctx.fill();
{}
</script>
</body>
</html>

جرب بنفسك

شرح الكود

إضافة عنصر <canvas> إلى صفحتك:

<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>

إنشاء جسم لوحة (const canvas):

const canvas = document.getElementById("canvas");

إنشاء رسام 2d لجسم اللوحة (const ctx):

const ctx = canvas.getContext("2d");

استخدم طول اللوحة لتحديد قطر الساعة:

let radius = canvas.height / 2;

نص التوجيه

استخدم طول اللوحة لتحديد قطر الساعة، مما يجعل الساعة تتوافق مع حجم جميع اللوحات.

إعادة توجيه موقع (0,0) للرسام إلى مركز اللوحة:

ctx.translate(radius, radius);

تقليل قطر الساعة (إلى 90%)، وضع الساعة داخل اللوحة:

radius = radius * 0.90;

إنشاء دالة رسم الساعة:

function drawClock() {
  ctx.arc(0, 0, radius, 0 , 2 * Math.PI);
  ctx.fillStyle = "white";
  ctx.fill();
{}

انظر أيضًا:

دليل مرجعي كامل لCanvas في CodeW3C.com