HTML Canvas Clock


HTML Canvas Clock: We are going to create analog clock using html canvas. We will create clock step by step with full example and demo.


Steps To Create HTML Canvas Clock

Here are Following Steps to create HTML Clock

Step 1 – Create Clock Canvas

Create Canvas for showing Clock and background-

Example :
<canvas id="clock-canvas" width="700" height="700"
style="background-color:red">
</canvas>

<script>
var clockCanvas = document.getElementById("clock-canvas");
var ctx = clockCanvas.getContext("2d");
var radius = clockCanvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawMyClock();

function drawMyClock() {
    ctx.arc(0, 0, radius, 0 , 2*Math.PI);
    ctx.fillStyle = "white";
    ctx.fill();
}
</script>

Try It »

Step 2 – Draw Numbers –

Example :
<canvas id="clock-canvas" width="700" height="700"
style="background-color:red">
</canvas>

<script>
var clockCanvas = document.getElementById("clock-canvas");
var ctx = clockCanvas.getContext("2d");
var radius = clockCanvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawMyClock();

function drawMyClock() {
    ctx.arc(0, 0, radius, 0 , 2*Math.PI);
    ctx.fillStyle = "white";
    ctx.fill();
    drawClockNumbers(ctx, radius);
}
function drawClockNumbers(ctx, clockRadius) {
    var angle;
    var timeCounter;
    ctx.font = clockRadius*0.16 + "px Verdana";
    ctx.textBaseline="top";
    ctx.textAlign="center";
    for(timeCounter= 1; timeCounter < 13; timeCounter++){
        ang = timeCounter * Math.PI / 6;
        ctx.rotate(angle);
        ctx.translate(0, -clockRadius*0.85);
        ctx.rotate(-ang);
        ctx.fillText(timeCounter.toString(), 0, 0);
        ctx.rotate(angle);
        ctx.translate(0, clockRadius*0.85);
        ctx.rotate(-angle);
    }
</script>

Try It »


Advertisements

Add Comment