时钟绘制的非常简易,但该有的都有了。
效果图如下,
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>clock</title> 6 <style> 7 body{ 8 background: #ddd; 9 } 10 #canvas { 11 margin: 10px; 12 padding: 10px; 13 background: #fff; 14 border: thin inset #aaa; 15 } 16 </style> 17 </head> 18 <body> 19 <canvas id="canvas" width="300" height="300"></canvas> 20 <script src="Example2-1.js"></script> 21 </body> 22 </html>
1 var canvas = document.getElementById("canvas"); 2 var context = canvas.getContext("2d"); 3 var FONT_HEIGHT = 15; 4 var MARGIN = 35; 5 var HAND_TRUNCATION = canvas.width/25; 6 var HOUR_HAND_TRUNCATION = canvas.width/10; 7 var NUMERAL_SPACING = 20; 8 var RADIUS = canvas.width/2 - MARGIN; 9 var HAND_RADIUS = RADIUS + NUMERAL_SPACING; 10 11 //绘制圆形 12 function drawCircle(){ 13 context.beginPath(); 14 context.arc(canvas.width/2,canvas.height/2,RADIUS,0,Math.PI*2,true); 15 //(圆心x坐标,圆心y坐标,半径,起点角,终点角,绘制方向(顺/逆)) 16 context.stroke(); 17 } 18 19 //绘制时刻数字 20 function drawNumberals(){ 21 var numerals = [1,2,3,4,5,6,7,8,9,10,11,12],angle = 0,numeralWidth = 0; 22 numerals.forEach(function(numeral){ 23 angle = Math.PI/6 * (numeral-3); 24 numeralWidth = context.measureText(numeral).width; 25 context.fillText(numeral, 26 canvas.width/2 + Math.cos(angle) * (HAND_RADIUS) - numeralWidth/2, 27 canvas.height/2 + Math.sin(angle) * (HAND_RADIUS) + FONT_HEIGHT/3); 28 }); 29 } 30 31 //画圆心 32 function drawCenter(){ 33 context.beginPath(); 34 context.arc(canvas.width/2,canvas.height/2,5,0,Math.PI*2,true); 35 context.fill(); 36 } 37 38 //画指针 39 function drawHand(loc,isHour){ 40 var angle = (Math.PI/2) * (loc/15)- Math.PI/2, 41 handRadius = isHour ? RADIUS -HAND_TRUNCATION -HOUR_HAND_TRUNCATION : RADIUS -HAND_TRUNCATION; 42 context.moveTo(canvas.width/2,canvas.height/2); 43 context.lineTo(canvas.width/2 + Math.cos(angle) * handRadius,canvas.height/2 + Math.sin(angle) * handRadius); 44 context.stroke(); 45 } 46 47 48 function drawHands(){ 49 var date = new Date, 50 hour = date.getHours(); 51 hour = hour > 12 ? hour - 12 : hour; 52 53 drawHand(hour*5 + (date.getMinutes()/60)*5,true); 54 drawHand(date.getMinutes(),false); 55 drawHand(date.getSeconds(),false); 56 } 57 58 function drawClock(){ 59 context.clearRect(0,0,canvas.width,canvas.height); //清空画布 60 61 drawCircle(); 62 drawCenter(); 63 drawHands(); 64 drawNumberals() 65 } 66 67 //初始化 68 context.font = FONT_HEIGHT + 'px Arial'; 69 loop = setInterval(drawClock,1000); //1s刷新一次