Khoa Nguyen Anh
Khoa Nguyen Anh

Reputation: 5

Javascript creating a clock

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Clock</title>
    </head>
    <body>
        <canvas id="canvas" width="500" height="500">
            This text is displayed if your browser does not support HTML5 Canvas.
        </canvas>
        <script type='text/javascript' src='Clock.js'></script>
    </body>
</html>

JavaScript

var canvas = document.getElementById("canvas"),
c = canvas.getContext("2d"),
Margin = 35,
NumbersRadius = canvas.width/2 - Margin,
ClockRadius = NumbersRadius - 30; 
//draw the circle that bound the clock 
function drawCircle() {
c.arc(canvas.width/2, canvas.height/2, ClockRadius, 0, 2*Math.PI);
c.stroke();}

//draw the numbers, which lie on the circle with radius: NumbersRadius
function drawNumbers(){
c.font = "25px Verdana";
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12],
angle;
numbers.forEach(function(numbers){
    angle = Math.PI/6 * (numbers - 3);
    c.fillText(numbers, canvas.width/2 + Math.cos(angle)*NumbersRadius, canvas.height/2 + Math.sin(angle)*NumbersRadius)
});}

//draw the hands
//length of each hand
var SecondHand = ClockRadius - 0.25*ClockRadius,
MinuteHand = SecondHand-0.25*SecondHand,
HourHand = MinuteHand-0.25*MinuteHand;
//Assume that we start at 3:00. i is the number of seconds

function drawHands() {
    var i = 0,
    angle = -1/30*Math.PI*i;
    //draw the SecondHand
    c.moveTo(canvas.width/2, canvas.height/2);
    c.lineTo(canvas.width/2 + Math.cos(angle)*ClockRadius, canvas.height/2 + Math.sin(angle)*ClockRadius);
    c.stroke();
    //draw the MinuteHand
    c.moveTo(canvas.width/2, canvas.height/2);
    c.lineTo(canvas.width/2 + Math.cos(-1/60*angle)*ClockRadius, canvas.height/2 + Math.sin(-1/60*angle)*ClockRadius);
    c.stroke;
    //draw the HourHand
    c.moveTo(canvas.width/2, canvas.height/2);
    c.lineTo(canvas.width/2 + Math.cos(-1/Math.pow(60,2)*angle)*ClockRadius, canvas.height/2 + Math.sin(-1/Math.pow(60,2)*angle*ClockRadius));
    c.stroke();
    i++;
}
function drawClock() {
    c.clearRect(0,0,canvas.width,canvas.height);
    drawCircle();
    drawNumbers();
    drawHands();
}

loop = setInterval(drawClock, 1000);

I don't know why my clock is not running. All the hands point and stay still at 3:00. The NumbersRadius is the radius of the circle that the coordinate of the numbers are on. The ClockRadius, which is smaller than NumbersRadius, is the radius of the circle that bound the hands.

Upvotes: 0

Views: 535

Answers (1)

Trevor Dixon
Trevor Dixon

Reputation: 24362

In drawHands, you're resetting i to 0 every time. Move var i = 0 outside that function.

var i = 0;
function drawHands() {
    var angle = -1/30*Math.PI*i;
    //draw the SecondHand
    c.moveTo(canvas.width/2, canvas.height/2);
...

http://jsfiddle.net/trevordixon/bW73Y/

Upvotes: 1

Related Questions