JavaScript analog clock with no images and no CSS

There are a lot JavaScript analog clocks out there, but most of them use images or CSS3 tricks to make them move.

I am showing you an analog clock made without any image and without any style thanks to Raphaël JavaScript Library.

Raphaël is a JavaScript library that let you your work with vector graphics on the web using the SVG W3C Recommendation and VML as a base for creating graphics which works on Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.

This is what we are going to create:

And as you can see from the source code there isn’t any image or CSS style as the clock is fully made with vectors.

let’s explore it in detail:

Line 6: loading Raphaël library

Line 10: creation of a canvas object called canvas on which we will draw the clock. The parameters are the id of the container (clock_id, you can find it at line 48), the width and the height of the object, in pixels

Line 11: drawing a circle called clock with center at 100,100 with a 95 pixels radius.

Line 12: setting some attributes for clock (the circle): fill":"#f5f5f5" will fill the circle with that color ,"stroke":"#444444" will decide the stroke color and "stroke-width":"5" is the width, in pixels, of the stroke.

Line 13: creating a variable called hour_sign that we’ll use to draw the hours.

Lines 14-20: the for loop goes through all 12 hours representable in a clock, uses trigonometry to find the starting and ending point of each hour sign, then uses path method to create a path element according to the string passed as argument which represents the path in SVG format. For more information about this format, check the official SVG docs. Anyway, it’s a very easy format since it follows the “move and line” theory, just like AS3.

If we look at line 21, which draws the hour hand

it can be translated into AS3 this way:

We keep drawing clock parts until line 29, using the same methods.

At line 30 we call update_clock function which will place all hands in the correct position according to your computer’s time, then at line 31 we make such function being executed at every second.

update_clock just determines current hours, minutes and seconds and updates the hands using rotate method which wants as arguments the amount of degrees to rotate the object and the center of rotation.

The degrees are determined by dividing 360 by the number of possible values (60 for seconds and minutes, 12 for hours) then multiplying such value by the current hours/minutes/seconds.

Hour hand is also rotated a bit more as minutes pass by, just like in real clocks.

Just notice the perfect code for the hour hand would be

rather than

but dividing minutes by 2.5 rather than 2 will make hour hand rotate slower and will give a better visual effect.

Hope you will like Raphaël JavaScript Library, I can show you how to make a little puzzle game with it if I receive a good feedback.

  • akineton

    thx, great work!

    p.s. it also worx on Opera Mobile 10. ;)

  • Fighterlegend

    Awesome! I didn’t know of this.

    Is there a problem with using setTimeout instead of setInterval?

  • I’m trying to digest as many HTML5 canvas examples as I can. This is a good one, thanks for the post!

  • This is pretty cool. Very impressive usage of Java Script.

    Technology has came so far since the old days of JS!

  • Pingback: Crear un reloj analógico con Javascript | SummArg()

  • Pingback: Crear un reloj analógico con Javascript | Blog personal de Brian Urban()

  • This looks fantastic and the library looks like it has lots of potential too, especially if it enables stuff like this to be made easily. The library seems like quite a big file to include in a web page if you’re only using it for this effect, though. I’ll look forward to seeing your puzzle game!

  • Nice , Without any images !

  • b3f3

    hi,
    thank you for this great work.
    Hhere is an enhancement that allows total control of parameters :


    function update_clock(width){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    hour_hand.rotate(30*hours+(minutes/2.5), width/2, width/2);
    minute_hand.rotate(6*minutes, width/2, width/2);
    second_hand.rotate(6*seconds, width/2, width/2);
    }

    function draw_clock(width, fillColor, strokeWidth, strokeColor, pinWidth, pinColor, hourHandLengh, hourHandColor, minuteHandLengh, minuteHandColor, secondHandLengh, secondHandExceeding, secondHandColor){
    canvas = Raphael("clock_id",width, width);
    var clock = canvas.circle(width/2,width/2,45);
    clock.attr({"fill":fillColor,"stroke":strokeColor,"stroke-width":strokeWidth})
    var hour_sign;
    for(i=0;i<12;i++){
    var start_x = width/2+Math.round(35*Math.cos(30*i*Math.PI/180));
    var start_y = width/2+Math.round(35*Math.sin(30*i*Math.PI/180));
    var end_x = width/2+Math.round(40*Math.cos(30*i*Math.PI/180));
    var end_y = width/2+Math.round(40*Math.sin(30*i*Math.PI/180));
    hour_sign = canvas.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y);
    }
    hour_hand = canvas.path("M"+width/2+" "+width/2+"L"+width/2+" "+((width/2)-hourHandLengh)+"");
    hour_hand.attr({stroke: hourHandColor, "stroke-width": 2});
    minute_hand = canvas.path("M"+width/2+" "+width/2+"L"+width/2+" "+((width/2)-minuteHandLengh)+"");
    minute_hand.attr({stroke: minuteHandColor, "stroke-width": 2});
    second_hand = canvas.path("M"+width/2+" "+((width/2)+secondHandExceeding)+"L"+width/2+" "+((width/2)-secondHandLengh)+"");
    second_hand.attr({stroke: secondHandColor, "stroke-width": 1});
    var pin = canvas.circle(width/2, width/2, pinWidth);
    pin.attr("fill", pinColor);
    update_clock(width)
    setInterval("update_clock("+width+")",1000);
    }

    To use it, you must call draw_clock() function with parameters :

    draw_clock(width, fillColor, strokeWidth, strokeColor, pinWidth, pinColor, hourHandLengh, hourHandColor, minuteHandLengh, minuteHandColor, secondHandLengh, secondHandExceeding, secondHandColor)

    For example :


    draw_clock(110, "#f5f5f5", 5, "#E18325", 4, "#000000", 25, "#444444", 32, "#444444", 35, 8, "#444444")

  • Kamala

    Hi,

    Thanks for your source code, however i need to change my clock size, i have changed the height and width of clock as you mentioned, it decreased the clock whole div size, but not actual clock.

    What i need to do? can you help me?

    Thanks
    Kamala

  • cvele

    Is it possible to show date and time in lower middle of clock or below the clock in various format?

    13:51:20
    04/Feb/2011

    or

    01:51:20 PM
    04 February 2011

    thanks

  • I’ve been working on an analog clock for a few days now. I’ve come nowhere close to this simple and workable solution.

    You are genius. I’m probably using it in my re-branded website which is under development. http://www.ganeshbaniya.com

    thanks a zillion

  • Doug Peterson

    Here is a modified version of the post earlier about the sizing. I made it so you just specify the width and it scales based on that. You can still color it, but this does the math for you:

    function update_clock(width)
    {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    hour_hand.rotate(30*hours+(minutes/2.5), width*.5, width*.5);
    minute_hand.rotate(6*minutes, width*.5, width*.5);
    second_hand.rotate(6*seconds, width*.5, width*.5);
    }

    function draw_clock(width, fillColor, strokeColor, pinColor, hourHandColor, minuteHandColor, secondHandColor)
    {
    canvas = Raphael(“clock_id”,width, width);
    var clock = canvas.circle(width*.5,width*.5, width * .475);
    clock.attr({“fill”:fillColor,”stroke”:strokeColor,”stroke-width”:(width*.025)})
    var hour_sign;
    for(i=0;i<12;i++){
    var start_x = width*.5+Math.round((width*.4)*Math.cos(30*i*Math.PI/180));
    var start_y = width*.5+Math.round((width*.4)*Math.sin(30*i*Math.PI/180));
    var end_x = width*.5+Math.round((width*.45)*Math.cos(30*i*Math.PI/180));
    var end_y = width*.5+Math.round((width*.45)*Math.sin(30*i*Math.PI/180));
    hour_sign = canvas.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y);
    }

    hour_hand = canvas.path("M" + width*.5 + " " + width*.5 + "L" + width*.5 + " " + (width*.25) + "");
    hour_hand.attr({stroke: hourHandColor, "stroke-width": width*.03});
    minute_hand = canvas.path("M" + width*.5 + " " + width*.5 + "L" + width*.5 + " " + (width*.2) + "");
    minute_hand.attr({stroke: minuteHandColor, "stroke-width": width*.02});
    second_hand = canvas.path("M" + width*.5 + " " + (width*.55) + "L" + width*.5 + " " + (width*.125) + "");
    second_hand.attr({stroke: secondHandColor, "stroke-width": width*.01});
    var pin = canvas.circle(width*.5, width*.5, width*.025);
    pin.attr("fill", pinColor);
    update_clock(width)
    setInterval("update_clock("+width+")",1000);

  • Doug Peterson

    Note on my post, I believe I didn’t capture the closing }, so be sure to add that.

  • Craig

    Is there a way to use Doug’s code to draw the clock again with the new colours, width etc. but delete the other clock before hand?

    At the moment if you call the function it draws another clock above the previous one.

  • Mathieu

    Cool stuff!
    It gave me the idea of creating my own colorful one:

    apps.mathieu-rodic.com/Beautiful/Clock

  • Mathieu

    Edit: sorry, I mistyped the link.

    http://apps.mathieu-rodic.com/Beautiful/Clock

  • banzemanga

    The only problem is that it requires Canvas and HTML5. I am trying to find a way to do it so that it is compatible even in old browsers.

  • This is an excellent clock, and the code engine driving it is just stupendous. For those of us on the design side, this is some real salvation, because it opens doors to a multitude of development options, for clients who want a clock running. I’ve already adapted this for two clients we’re working on, and one is a watch company! The other is a parking lot rental agency, and people visiting the site may want the clock as a reference.

    The two examples are here: http://galleria.rodanclient.com and http://npf.rodanclient.com; and you can see the original script in action on a splash page at http://galleriawatches.com.

  • Alosa

    How can I set it to run in different time zone? Say GMT+2?

  • ceakki

    Hi! Nice clock :)

    @Doug Peterson: I added next line to your code:

    hour_sign.attr({stroke: hourSignColor, “stroke-width”: width*.03});

    and I modified this:

    function draw_clock(width, fillColor, strokeColor, pinColor, hourSignColor, hourHandColor, minuteHandColor, secondHandColor)

    Now you can change the color of “hour_sign”.

    Regards!

  • Hi,
    Thanks for excellent work. Can I have more than 1 clock o the page? I used code like this – http://pastebin.com/hVeaL4mj but only one clock is updating.
    Sorry, for noob question.

  • Pingback: Time they say is the great healer… « Eoin O'Connor's Blog()

  • Stephan

    I was wondering how I can add two clocks to one website? I am trying to do something specific. How can I add two times the Javascript, without gettin a Script Conflict?

  • jser

    clocks’ hands are malfunctioning when i tried the code
    does rafael js needs prototype?

  • jser

    var prevhr = 0;
    var prevmin = 0;
    var prevsecseconds = 0;
    function draw_clock(){
    canvas = Raphael(“clock_id”,200, 200);
    var clock = canvas.circle(100,100,95);
    clock.attr({“fill”:”#f5f5f5″,”stroke”:”#444444″,”stroke-width”:”5″})
    var hour_sign;
    for(i=0;i<12;i++){
    var start_x = 100+Math.round(80*Math.cos(30*i*Math.PI/180));
    var start_y = 100+Math.round(80*Math.sin(30*i*Math.PI/180));
    var end_x = 100+Math.round(90*Math.cos(30*i*Math.PI/180));
    var end_y = 100+Math.round(90*Math.sin(30*i*Math.PI/180));
    hour_sign = canvas.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y);
    }
    hour_hand = canvas.path("M100 100L100 50");
    hour_hand.attr({stroke: "#444444", "stroke-width": 6});
    minute_hand = canvas.path("M100 100L100 40");
    minute_hand.attr({stroke: "#444444", "stroke-width": 4});
    second_hand = canvas.path("M100 110L100 25");
    second_hand.attr({stroke: "#444444", "stroke-width": 2});
    var pin = canvas.circle(100, 100, 7);
    pin.attr("fill", "#000000");
    update_clock();

    setInterval("update_clock()",1000);
    }

    function update_clock(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();

    prevhr = 360 – prevhr;
    hour_hand.rotate(prevhr, 100, 100);
    prevmin = 360 – prevmin;
    minute_hand.rotate(prevmin, 100, 100);
    prevsecseconds = 360 – prevsecseconds;
    second_hand.rotate(prevsecseconds, 100, 100);

    hour_hand.rotate(30*hours+(minutes/2.5), 100, 100);
    minute_hand.rotate(6*minutes, 100, 100);
    second_hand.rotate(6*seconds, 100, 100);

    prevhr = 30*hours+(minutes/2.5);
    prevmin = 6*minutes;
    prevsecseconds = 6*seconds;

    }

  • Ben

    Hi – this clock code uses Raphael version 1.4.3. The current version of Raphael is 2.0.1. As you might have guessed, this clock doesn’t work with Raphael 2.0.1. If you just want to make this clock work, copy the version of Raphael that the example uses (http://www.emanueleferonato.com/stuff/triquiclock/raphael-min.js).

  • Manoj Mittal

    Hi,

    awesome work..
    Raphaël JavaScript Library. is it free or licenced ?
    AS per above mention query of Alosa,
    Can any one help out .. How can I set it to run in different time zone? Say GMT+2?

    Thnaks in Advance

  • Hey,

    thanks for the great script!
    I made a fix for the new version of raphaels js.
    Becouse rotating an object is changed.

    /* http://raphaeljs.com/ JavaScript Library !!!! */
    /* clock thanks to: http://www.emanueleferonato.com/2010/12/11/javascript-analog-clock-with-no-images-and-no-css/ */
    <!–
    var hours = 0;
    var minutes = 0;
    var seconds = 0;
    function draw_clock(){
    canvas = Raphael("clock_id",80,45);
    var clock = canvas.ellipse(40,23,35,19);
    clock.attr( /*{"fill":"#93B300","stroke":"#444444","stroke-width":"2"})*/
    {
    gradient: '90-#364200-#93B300',
    stroke: '#444444','stroke-width': 2,'stroke-linejoin': 'round',
    rotation: -90,
    });
    var rond = canvas.circle(40, 23, 19);
    rond.attr(
    {
    stroke: '#444444','stroke-width': 1, 'stroke-linejoin': 'round',
    fill: '#93B300',
    });

    var hour_sign;
    for(i=0;i

  • Delete the old post plz :P
    changed the script too much.

    thanks for the great script!
    I made a fix for the new version of raphaels js.
    Becouse rotating an object is changed.

    code:

    var hours = 0;
    var minutes = 0;
    var seconds = 0;
    (put these tree lines above:”function draw_clock(){ ” in the beginning of your script)

    function update_clock(){

    hour_hand.rotate(-(30*hours+(minutes/2.5)), 40, 23);
    minute_hand.rotate(-(6*minutes), 40, 23);
    second_hand.rotate(-(6*seconds), 40, 23);

    now = new Date();
    hours = now.getHours();
    minutes = now.getMinutes();
    seconds = now.getSeconds();

    hour_hand.rotate(30*hours+(minutes/2.5), 40, 23);
    minute_hand.rotate(6*minutes, 40, 23);
    second_hand.rotate(6*seconds, 40, 23);
    }

  • dasarath sahoo

    thx for great script, working fine, but i have a little problem. i want to reduce the size of clock, how is it possible , kindly support

  • This is the only clock that fits my needs exactly and is very lightweight compared to other options I have found and does not require transform. Im dying to have it possible to fit multiple clocks in one page with a UTC offset. I need it to display different time zones. Any help with this is GREATLY appreciated!

  • Can you tell me how can i import 3 clocks in a same web page and also how can i change the clock to show different timezones ? Thanks.

  • update: I imported the clocks but they aren’t working, just one clock is working.

  • I want to show multiple clocks also — have you figured that out yet?

  • A fix for the time issue and updated raphael js that works for me is as follows:

    create two external variables (place them outside of any function calls) –>

    var currentsecond = 0;
    var currentminute = 0;

    Then change the first “update_clock” method to something else (I call it first_clock here). The purpose is to set the initial time. These calls are in the “draw_clock” method.


    first_clock(width);
    setInterval("update_clock("+width+")",1000);

    Now copy the original code for “update_clock” into the newly created method:


    function first_clock(width){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    second_hand.rotate(6*seconds, width/2, width/2);
    minute_hand.rotate(6*minutes, width/2, width/2);
    hour_hand.rotate(30*hours, width/2, width/2);
    }

    And finally, create a couple of if statements that update the minute and second hands at the appropriate time. The old time being stored in the external variables you previously created. The second hand simply updates to one second everytime:


    function update_clock(width){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    thissecond = seconds;
    second_hand.rotate(6, width/2, width/2);
    if ( ++currentsecond%60 == 0){
    minute_hand.rotate(6, width/2, width/2);}
    if( ++currentminute%60 == 0){
    hour_hand.rotate(30, width/2, width/2); }
    }

  • Update to my previous post…

    The previous “update_clock” method was flawed. I was updating current minutes with every second. Previously I also had a variable called “thissecond” which should have been “currentsecond”. In the revision, I give “currentminute” the value of “minutes” in the “first_clock()” method. Then instead of calculating modulus, I simply inquire as to whether either the seconds or minutes have reached 60. If they have, I reset the corresponding time indicator (ie. seconds or minutes) and update the clock. This time, I only update the “currentminute” variable if the “currentsecond” variable has reached it’s max value, 60.

    Below is the revised code, sorry:


    function first_clock(width) {
    /* PREVIOUS CODE ... */
    currentminute = minutes;
    }
    function update_clock(width){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    currentsecond = seconds;
    second_hand.rotate(6, width/2, width/2);
    if ( ++currentsecond == 60){
    minute_hand.rotate(6, width/2, width/2);
    currentsecond = 0;
    currentminute++;
    }
    if( currentminute == 60){
    hour_hand.rotate(30, width/2, width/2);
    currentminute = 0;
    }
    }

  • Last update…

    The “currentsecond” variable can be removed altogether, everywhere it is listed. Then in the place of “if(++currentsecond == 60)“, you would instead put “if( seconds == 60 )“.

  • Nathaniel Grammel

    Nice clock! As far as the updated Raphael issue, there’s a simpler solution than keeping track of extra variables.
    Take a look at Raphael’s documentation: rotate is deprecated in favor of transform. A simpler fix is to replace the three “rotate” lines in update_clock() with transform (see http://raphaeljs.com/reference.html#Element.transform):

    hour_hand.transform(“r” + 30*hours+(minutes/2.5) + “, 100, 100″);
    minute_hand.transform(“r” + 6*minutes + “, 100, 100″);
    second_hand.transform(“r” + 6*seconds + “, 100, 100″);

  • Nathaniel Grammel

    Apologies, the hour_hand.transform line should be:

    hour_hand.transform(“r” + (30*hours+(minutes/2.5)) + “, 100, 100?);

  • Dennis

    Wow! Great script. Even works on my iPad, where most javascripts fail.

    I tweeked it a bit to work on my neighborhood watch information page, incorporating it to display over a version of our neighborhood town clock (http://www.nortongulch.com/images/larchmontblvd.jpg) and can be seen at http://www.nortongulch.com/larchmontlinks.php.

    Does anybody know how to exactly how to position the clock? I had to cheat and place the clock in a table and force a downward alignment by using a clear image in a above the clock.

  • vasanth

    Nice Script…

    Can i modify the image of clock ???

  • Pete WIlson

    Nathaniel’s method works for me with some minor changes as follows:

    hour_hand.transform(‘r’ + (30*hours+(minutes/2.5)) + ‘, 100, 100?’);
    minute_hand.transform(‘r’ + 6*minutes + ‘, 100, 100′);
    second_hand.transform(‘r’ + 6*seconds + ‘, 100, 100′);

    So the complete script – working for raphael v2.0.1 is:

    Triqui Clock

    function draw_clock(){
    canvas = Raphael(“clock_id”,200, 200);
    var clock = canvas.circle(100,100,95);
    clock.attr({“fill”:”#f5f5f5″,”stroke”:”#444444″,”stroke-width”:”5″})
    var hour_sign;
    for(i=0;i<12;i++){
    var start_x = 100+Math.round(80*Math.cos(30*i*Math.PI/180));
    var start_y = 100+Math.round(80*Math.sin(30*i*Math.PI/180));
    var end_x = 100+Math.round(90*Math.cos(30*i*Math.PI/180));
    var end_y = 100+Math.round(90*Math.sin(30*i*Math.PI/180));
    hour_sign = canvas.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y);
    }
    hour_hand = canvas.path("M100 100L100 50");
    hour_hand.attr({stroke: "#444444", "stroke-width": 6});
    minute_hand = canvas.path("M100 100L100 40");
    minute_hand.attr({stroke: "#444444", "stroke-width": 4});
    second_hand = canvas.path("M100 110L100 25");
    second_hand.attr({stroke: "#444444", "stroke-width": 2});
    var pin = canvas.circle(100, 100, 5);
    pin.attr("fill", "#000000");
    update_clock()
    setInterval("update_clock()",1000);
    }

    function update_clock(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    hour_hand.transform('r' + (30*hours+(minutes/2.5)) + ', 100, 100?');
    minute_hand.transform('r' + 6*minutes + ', 100, 100');
    second_hand.transform('r' + 6*seconds + ', 100, 100');

    }

    draw_clock()

    Incidentally I have linked to raphael externally here – http://cdnjs.cloudflare.com/ajax/libs/raphael/2.0.1/raphael-min.js

    :-)

  • tthensley

    Did anyone ever find a solution to display more than one clock at a time? I’d like to display multiple clocks to show different time zones at a glance.

    For those asking abou thte time zones, you can update the time zone by simply adjusting var hours = now.getHours(); in the update_clock method with +/- the number of hours you want to adjust. For example…

    var hours = now.getHours()+1;

    moves hours ahead 1,

    var hours = now.getHours()-2;

    moves hours back 2…

    Great script, thanks!

  • How do I have the multiple clocks with different dates of my own.

    for i.e

    function update_clock(myOwnDate) {
    var now = myOwnDate;
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    hour_hand.rotate(30*hours+(minutes/2.5), 100, 100);
    minute_hand.rotate(6*minutes, 100, 100);
    second_hand.rotate(6*seconds, 100, 100);
    }

    I tried calling this method wrapped inside the setInterval function by creating different objects of clocks. The clock is displaying but it never rotates. Do you have any idea.

  • Can the second hand be modified to be a smoother sweep?

  • chris

    My clock does not update properly.
    http://tophelabs.com/clock/

    It was like this even before I started modifying it.

    Can someone please help?

    Thanks!

  • Jon

    I had to fall back to version 1.52 of raphael-min.js to stop the clock from jmping around randomly:

    https://github.com/DmitryBaranovskiy/raphael/blob/dbe241f4c5310dd9bf3b451c538d78c6c4a0e288/raphael-min.js

  • chris

    thank you Jon!

  • Amaru

    That is great, really. I did not expect making a js clock may be that easy. The library itself seems to be very useful and I can imagine at least several ideas of how to use it for my purposes. However there is a problem with the script. I don’t know what is wrong cause it works fine on this website. I tried the code myself, easily resized and customized the clock, but it does not work like a real clock.

    Equation: 6*seconds calculates rotation angle measured between the current clock pointer and “zero” position (noon, 12 o’clock)…. This would work if the rotation was using absolute angle. Unfortunately it seems it uses the relative. The rotation starts where the pointer was directed a second ago. For instance: we have 20th second on the clock (120 deg rotation), the next second is 6*second = 6*21 = 126 degree but starting from 120 degree. After 21th second the pointer has 120 + 126 = 246 degree rotation, that means it indicates 41st second o’clock.
    All three pointers go like crazy. I can record a screen to share it on demand.

    If I want a pointer to work properly I need to set the rotation angle to fixed value. Then the pointer goes ok, but each time I run the script it starts from zero (noon/midnight) so it works like a stop watch rather than a clock. How to make the pointer to rotate properly and indicating the actual, real time?

    Any idea how to solve it?

  • Jake

    For those wanting to have multiple clocks on one page, the below code works :

    function draw_clock(id) {
    canvas = Raphael(id,200, 200);
    var clock = canvas.circle(100,100,95);
    clock.attr({“fill”:”#f5f5f5″,”stroke”:”#444444″,”stroke-width”:”5″})
    var hour_sign;
    for(i=0;i<12;i++) {
    var start_x = 100+Math.round(80*Math.cos(30*i*Math.PI/180));
    var start_y = 100+Math.round(80*Math.sin(30*i*Math.PI/180));
    var end_x = 100+Math.round(90*Math.cos(30*i*Math.PI/180));
    var end_y = 100+Math.round(90*Math.sin(30*i*Math.PI/180));
    hour_sign = canvas.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y);
    }

    var hh = canvas.path("M100 100L100 50");
    hh.attr({stroke: "#444444", "stroke-width": 6});

    var mh = canvas.path("M100 100L100 40");
    mh.attr({stroke: "#444444", "stroke-width": 4});

    var sh = canvas.path("M100 110L100 25");
    sh.attr({stroke: "#444444", "stroke-width": 2});

    var pin = canvas.circle(100, 100, 5);
    pin.attr("fill", "#000000");

    update_clock(hh, mh, sh);
    setInterval(function() { update_clock(hh, mh, sh); },1000);
    }
    function update_clock(hhGiven, mhGiven, shGiven) {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();

    hhGiven.transform("r" + (30*hours+(minutes/2.5)) + ", 100, 100");
    mhGiven.transform("r" + 6*minutes + ", 100, 100");
    shGiven.transform("r" + 6*seconds + ", 100, 100");
    }

    You have to pass the "id" of the div to the draw_clock() function, then set the hh (hour_hand), mh (minute_hand) and sh (second_hand) variables to be local to the current method, and pass these to the update_clock() function so that only the current clocks items are passed.

    Hope this helps everyone

  • I’ve been looking for an analog Javascript clock like this for ages because my site uses a clock with a pieface as its logo. But when I tried it, the clock appears on the screen, but the clock hands jump around wildly on each tick. I simply downloaded your rapheal.js and cut and pasted your source code above without any changes. I’m running on Firefox 22.0 and Windows 7 Home Premium. Is there something wrong with that?

  • Jake

    @Fredshay

    If you are using the most recent version of Raphael.js then switch the following lines of code:
    hour_hand.rotate(30*hours+(minutes/2.5), 100, 100);
    minute_hand.rotate(6*minutes, 100, 100);
    second_hand.rotate(6*seconds, 100, 100);

    to be :
    hour_hand.transform(“r” + (30*hours+(minutes/2.5)) + “, 100, 100″);
    minute_hand.transform(“r” + 6*minutes + “, 100, 100″);
    second_hand.transform(“r” + 6*seconds + “, 100, 100″);

    I believe the rotate method was changed to have a different functionality, the transform method supplies the same functionality as the old rotate method did.

    http://raphaeljs.com/reference.html#Element.rotate

    • Afshin

      thank you so much.

  • Pingback: [?????,SVG] ???? CSS?? ??????? ???? ?? ??? | ??? ? ?????()

  • Andrew

    Can anyone post the code to update this clock with a custom defined time ? Not the system time. For an instance : clock(‘3:03:10′); So the clock should works from the defined time. Please Help ! Thanks for the great script !

  • Thank you all very much! In special Emanuele Feronato, and @Jake for the update!

  • Max

    Hi currently using the code below, but the hands are not directly in the center dot, any suggestions? much appreciated.

    drawClock: function(width, fillColor, strokeColor, pinColor, hourHandColor, minuteHandColor, secondHandColor){
    var self = this;
    canvas = Raphael(“clock”,width, width);
    var clock = canvas.circle(width*.5,width*.5, width * .475);
    clock.attr({“fill”:fillColor,”stroke”:strokeColor,”stroke-width”:(width*.025)})
    var hour_sign;
    for(i=0;i<12;i++){
    var start_x = width*.5+Math.round((width*.4)*Math.cos(30*i*Math.PI/180));
    var start_y = width*.5+Math.round((width*.4)*Math.sin(30*i*Math.PI/180));
    var end_x = width*.5+Math.round((width*.45)*Math.cos(30*i*Math.PI/180));
    var end_y = width*.5+Math.round((width*.45)*Math.sin(30*i*Math.PI/180));
    hour_sign = canvas.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y);
    }
    hour_hand = canvas.path("M" + width*.5 + " " + width*.5 + "L" + width*.5 + " " + (width*.25) + "");
    hour_hand.attr({stroke: hourHandColor, "stroke-width": width*.03});
    minute_hand = canvas.path("M" + width*.5 + " " + width*.5 + "L" + width*.5 + " " + (width*.2) + "");
    minute_hand.attr({stroke: minuteHandColor, "stroke-width": width*.02});
    second_hand = canvas.path("M" + width*.5 + " " + (width*.55) + "L" + width*.5 + " " + (width*.125) + "");
    second_hand.attr({stroke: secondHandColor, "stroke-width": width*.01});
    var pin = canvas.circle(width*.5, width*.5, width*.025);
    pin.attr("fill", pinColor);

    self.updateClock(width)
    setInterval(self.updateClock("+width+"),1000);
    },

    updateClock: function(width){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    hour_hand.rotate(30*hours+(minutes/2.5), width*.5, width*.5);
    minute_hand.rotate(6*minutes, width*.5, width*.5);
    second_hand.rotate(6*seconds, width*.5, width*.5);
    }
    }

    • Max

      Ignore that found fix :

      setInterval(self.updateClock(“+width+”),1000);

      to

      setInterval(self.updateClock(width),1000);

  • mukunda

    Thank you …. this clock is wooaww . #Greatcode

  • Pingback: Square Analog Clock with Raphaeljs - HTML CODE()

  • Chuck

    Anyway to add buttons which change the hands like a real analogue clock would have?

    E.G. One button to increase the time (the hands would spin round clockwise faster) and one to rewind the time?

  • Great tuts…

    how to drag hour and minits via mouse, could you help me?