Javascript创建一个时钟

时间:2013-08-13 03:45:18

标签: javascript loops setinterval

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

我不知道为什么我的时钟没有运行。所有的手指向并保持在3点。 NumbersRadius是数字坐标所在圆的半径。 ClockRadius小于NumbersRadius,是绑定手的圆的半径。

1 个答案:

答案 0 :(得分:1)

drawHands中,您每次都将i重置为0。将var i = 0移到该功能之外。

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/