1.用canvas画一个时钟。

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } .box{ width: 300px; height: 300px; margin: 0 auto; margin-top: 100px; /*border: 1px solid black;*/ } </style> </head> <body> <div class="box"> <canvas id="canvas" width="300px" height="300px"></canvas> </div> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext('2d'); run(); setInterval(run,1000); function run(){ var time = new Date();//获取现在时间 var sec = time.getSeconds();//获取秒 var min = time.getMinutes();//获取分钟 var hour = time.getHours();//获取小时 hour = hour>12 ? hour-12 : hour; ctx.clearRect(0,0,300,300);//清楚画布,准备重新画 ctx.save();//保存初始状态值 ctx.beginPath();//轨迹开始 ctx.lineWidth = 3;//设置线条宽度 ctx.arc(150,150,130,0,2*Math.PI);//画一个圆 var color = ctx.createRadialGradient(150,150,30,150,150,100);//渐变样式 color.addColorStop(0.0,"rgb(48, 209, 219)"); color.addColorStop(1.0,"rgb(30, 231, 116)"); ctx.fillStyle = color;//填充前面设置的效果 ctx.fill(); ctx.strokeStyle = "aqua";//线条颜色 ctx.stroke(); ctx.restore();//保存状态 ctx.save();//放到堆中留着调用 ctx.translate(150,150);//移动准备画下面的东西 for(var i=0; i<60; i++){ if(i%5 == 0){//画十二个时间点 ctx.beginPath(); ctx.moveTo(0,120); ctx.lineTo(0,130); ctx.lineWidth = 5; ctx.strokeStyle = "blue"; ctx.stroke(); ctx.rotate(Math.PI/30); }else{//画分钟点 ctx.beginPath(); ctx.moveTo(0,120); ctx.lineTo(0,126); ctx.lineWidth = 1; ctx.strokeStyle = "cornflowerblue"; ctx.stroke(); ctx.rotate(Math.PI/30); } } ctx.restore(); //秒针 ctx.save(); ctx.translate(150,150); ctx.rotate(sec*Math.PI/30); ctx.beginPath(); ctx.moveTo(0,30); ctx.lineTo(0,-120); ctx.lineWidth = 1; ctx.strokeStyle = "red"; ctx.stroke(); ctx.restore(); //分针 ctx.save(); ctx.translate(150,150); ctx.rotate(sec*Math.PI/1800 + min*Math.PI/30);//每一秒再分60分,秒针走一刻度,分针要走1/60刻度,sec*(6*Math.PI/180)/60 ctx.beginPath(); ctx.moveTo(0,20); ctx.lineTo(0,-100); ctx.lineWidth = 2; ctx.strokeStyle = "yellow"; ctx.stroke(); ctx.restore(); //时针 ctx.save(); ctx.translate(150,150); ctx.rotate(min*Math.PI/360 + hour*Math.PI/6);//每一小时走过5个刻度线,60分钟,30deg,分成60份,30deg/60 ctx.beginPath(); ctx.moveTo(0,10); ctx.lineTo(0,-80); ctx.lineWidth = 3; ctx.strokeStyle = "black"; ctx.stroke(); ctx.restore(); } </script> </body> </html>