Question

I would like to make a circular clock with HTML and JS, using the <canvas>. I wrote this code:

function updateClock ()
    {
        // Variables for the time
        var currentTime = new Date();

        var currentHours = currentTime.getHours();
        var currentMinutes = currentTime.getMinutes();
        var currentSeconds = currentTime.getSeconds();
        // Convert time variable in RADs
        var RADcurrentTime = {
            hours : currentHours * Math.PI * 2 / 24,
            minutes : currentMinutes * Math.PI * 2 / 60,
            seconds : currentSeconds * Math.PI * 2 / 60
        };
        // Compose the circle clock
        var clock_canvas = document.getElementById("clock");
        var context = clock_canvas.getContext("2d");

        var hours_radius = 70;
        context.beginPath();
        context.arc(screen.availWidth/2, screen.availHeight/2, hours_radius, 0, RADcurrentTime.hours);
        context.closePath();
        context.lineWidth = 3;
        context.stroke();

        var minutes_radius = 50;
        context.beginPath();
        context.arc(screen.availWidth/2, screen.availHeight/2, minutes_radius, 0, RADcurrentTime.minutes);
        context.closePath();
        context.lineWidth = 3;
        context.stroke();

        var seconds_radius = 30;
        context.beginPath();
        context.arc(screen.availWidth/2, screen.availHeight/2, seconds_radius, 0, RADcurrentTime.seconds);
        context.closePath();
        context.lineWidth = 3;
        context.stroke();
        `

but it doesn't work. I put in the body tag onload="updateClock(); setInterval('updateClock()', 1000 )" and it still doesn't work. The only thing I get is a white screen... Anyone can help me suggesting the cause?

Was it helpful?

Solution

You are not drawing your content relative to canvas but to screen which could result in a very different offset.

If your canvas is lets say 200 pixels wide and high and your screen is 1920x1080 then half of that would draw the clock from center point 960, 540, ie. way outside the limits of the canvas of (here) 200x200.

Instead of this:

context.arc(screen.availWidth/2,screen.availHeight/2, hours_radius, 0, RADcurrentTime.hours);

use something like this (assuming canvas is square size):

context.arc(canvas.width/2, canvas.height/2,hours_radius,0,RADcurrentTime.hours);
            ^^^^^^^^^^^^    ^^^^^^^^^^^^^

You may also get some useful input from this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top