直接上代码:
<!DOCTYPE html> <html > <head> <meta charset="utf-8" /> <title>HTML5时钟</title> <style type="text/css"> .clocks { height: 500px; margin: 25px auto; position: relative; width: 500px; } </style> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <div> <canvas id="canvas" width="500" height="500"></canvas> </div> <script type="text/javascript"> var canvas,ctx; var clockRadius = 240; var clockImage; //清除画的内容 function clear(){ ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); } //画时钟 function drawScene(){ clear(); var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); hours = hours>12 ? hours-12:hours; var hour = hours + minutes / 60; var minute = minutes + seconds/60; ctx.save(); // ctx.drawImage(clockImage,0,0,500,500); //设置原点 ctx.translate(canvas.width/2,canvas.height/2); ctx.beginPath(); ctx.font='36px Arial'; ctx.fillStyle="#000"; ctx.textAlign='center'; ctx.textBaseline = 'middle'; //画小时 for(var n=1 ; n <=12 ;n++){ var theta = (n-3)*(Math.PI*2)/12; var x = clockRadius*0.8*Math.cos(theta); var y = clockRadius*0.8*Math.sin(theta); ctx.fillText(n,x,y); } ctx.save(); //画刻度 for(var n = 0 ; n < 60 ; n++){ var theta =(n-15) * 2 * Math.PI / 60; var x = clockRadius*Math.cos(theta); var y = clockRadius*Math.sin(theta); ctx.beginPath(); if(n == 0 || n == 15 || n == 30 || n == 45){ ctx.translate(x,y); ctx.rotate(theta); ctx.moveTo(-25,-2); ctx.lineTo(-25,2); ctx.lineTo(5,5); ctx.lineTo(5,-5); }else if(n==5||n == 10||n == 20||n==25||n==35||n==40||n==50||n==55){ ctx.translate(x,y); ctx.rotate(theta); ctx.moveTo(-15,-2); ctx.lineTo(-15,2); ctx.lineTo(5,5); ctx.lineTo(5,-5); }else{ ctx.arc(x,y,5,0,2*Math.PI); } ctx.fill(); ctx.restore(); ctx.save(); } //绘制时针 var theta = (hour-3)*2*Math.PI/12; ctx.rotate(theta); ctx.beginPath(); ctx.moveTo(-15,-5); ctx.lineTo(-15,5); ctx.lineTo(clockRadius*0.5,1); ctx.lineTo(clockRadius*0.5,-1); ctx.fill(); ctx.restore(); ctx.save(); //绘制分针 theta = (minute - 15 ) * 2 * Math.PI /60; ctx.rotate(theta); ctx.beginPath(); ctx.moveTo(-15,-4); ctx.lineTo(-15,4); ctx.lineTo(clockRadius*0.7,1); ctx.lineTo(clockRadius*0.7,-1); ctx.fill(); ctx.restore(); ctx.save(); //绘制秒针 theta = (seconds - 15 + 0)*2*Math.PI / 60; ctx.rotate(theta); ctx.beginPath(); ctx.moveTo(-15,-3); ctx.lineTo(-15,3); ctx.lineTo(clockRadius*0.9,1); ctx.lineTo(clockRadius*0.9,-1); ctx.fill(); ctx.restore(); ctx.restore(); } $(function(){ canvas = document.getElementById('canvas'); if(canvas.getContext){ ctx = canvas.getContext('2d'); clockImage = new Image(); clockImage.src = './cface.png'; // drawScene(); setInterval(drawScene,1000); } }) </script> </body> </html>