ล่าสุดการพัฒนาเว็บบทเรียน
 

Canvasหน้าปัดนาฬิกา


Part II - วาดหน้าปัดนาฬิกา

ต้องการนาฬิกาหน้าปัดนาฬิกา สร้างฟังก์ชัน JavaScript เพื่อวาดใบหน้านาฬิกา:

javascript:

function drawClock() {
    drawFace(ctx, radius);
}

function drawFace(ctx, radius) {
    var grad;

    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, 2*Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();

    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.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);

สร้าง 3 สถานีสีที่สอดคล้องกับชั้นกลางและขอบด้านนอกของส่วนโค้ง:

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();