ตัวเลขนาฬิกา Canvas
- หน้าก่อน คำอธิบายนาฬิกา
- หน้าต่อไป ตัวเลขนาฬิกา
ส่วนที่ 2 - วาดผิวนาฬิกา
นาฬิกาต้องการผิวนาฬิกา。สร้างฟังก์ชัน JavaScript ที่จะวาดผิวนาฬิกา:
JavaScript:
function drawClock() { drawFace(ctx, radius); } function drawFace(ctx, radius) { const grad = ctx.createRadialGradient(0, 0 ,radius * 0.95, 0, 0, radius * 1.05); grad.addColorStop(0, '#333'); grad.addColorStop(0.5, 'white'); grad.addColorStop(1, '#333'); ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = 'white'; ctx.fill(); ctx.strokeStyle = grad; ctx.lineWidth = radius*0.1; ctx.stroke(); ctx.beginPath(); ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); ctx.fillStyle = '#333'; ctx.fill(); }
การอธิบายรหัส
สร้างฟังก์ชัน drawFace() ที่จะวาดผิวนาฬิกา:
function drawClock() { drawFace(ctx, radius); } function drawFace(ctx, radius) { }
วาดวงกลมสีขาว:
ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = 'white'; ctx.fill();
สร้างกราดิเอนท์ทางรัศมี (95% และ 105% ของรัศมีนาฬิกาตัวเดิม):
grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);
สร้างสามสีที่เหมือนกัน ตามลำดับเป็นขอบด้านด้านในของโค้งเขตวงกลม, ขอบด้านกลางและขอบด้านด้านนอกของวงกลม:
grad.addColorStop(0, '#333'); grad.addColorStop(0.5, 'white'); grad.addColorStop(1, '#333');
คำเตือน: สีที่มีสามสีนี้สามารถสร้างภาพ 3D ได้:
กำหนดสีที่เรียกเรียงของสายวาดสำหรับวัตถุวาด:
ctx.strokeStyle = grad;
กำหนดความกว้างของสายวาดสำหรับวัตถุวาด (10% ของรัศมี):
ctx.lineWidth = radius * 0.1;
วาดวงกลม:
ctx.stroke();
วาดจุดกลางของนาฬิกา:
ctx.beginPath(); ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); ctx.fillStyle = '#333'; ctx.fill();
อ่านเพิ่มเติม:
- หน้าก่อน คำอธิบายนาฬิกา
- หน้าต่อไป ตัวเลขนาฬิกา