loops - Javascript creating a clock -
html
<!doctype html> <html> <head> <title>clock</title> </head> <body> <canvas id="canvas" width="500" height="500"> text displayed if browser 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 circle bound clock function drawcircle() { c.arc(canvas.width/2, canvas.height/2, clockradius, 0, 2*math.pi); c.stroke();} //draw numbers, lie on circle 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 hands //length of each hand var secondhand = clockradius - 0.25*clockradius, minutehand = secondhand-0.25*secondhand, hourhand = minutehand-0.25*minutehand; //assume start @ 3:00. number of seconds function drawhands() { var = 0, angle = -1/30*math.pi*i; //draw 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 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 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 clock not running. hands point , stay still @ 3:00. numbersradius radius of circle coordinate of numbers on. clockradius, smaller numbersradius, radius of circle bound hands.
in drawhands
, you're resetting i
0 every time. move var = 0
outside function.
var = 0; function drawhands() { var angle = -1/30*math.pi*i; //draw secondhand c.moveto(canvas.width/2, canvas.height/2); ...
Comments
Post a Comment