0

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:00 保持静止。NumbersRadius 是数字坐标所在的圆的半径。小于 NumbersRadius 的 ClockRadius 是包围双手的圆的半径。

4

1 回答 1

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/

于 2013-08-13T03:52:55.083 回答