最近在对Html5比较感兴趣,就用空闲时间做一些小例子进行练习,今天绘制一个走动的时钟,具体如下图所示:
具体思路在上图已有说明,代码如下:
1 <script type="text/javascript"> circle(ctx, x, y, r, st, end, w) { 5 ctx.lineWidth = w; 6 ctx.beginPath(); 7 ctx.moveTo(x, y); 8 ctx.arc(x, y, r, st, end, true); 9 ctx.stroke(); 10 } circle0(ctx, x, y, r, st, end) { 14 ctx.fillStyle = "#ffffff"; 15 ctx.beginPath(); 16 ctx.arc(x, y, r, st, end, true); 17 ctx.fill(); 18 } 19 function circle1(ctx, x, y, r, st, end, w) { 20 ctx.strokeStyle = "gray"; 21 ctx.lineWidth = w; 22 ctx.beginPath(); 23 ctx.arc(x, y, r, st, end, true); 24 ctx.stroke(); 25 } line(ctx, x1, y1, x2, y2, w) { 29 if (w == 1) { 30 ctx.strokeStyle = "red"; 31 } else if (w == 2) { 32 ctx.strokeStyle = "blue"; 33 } else { 34 ctx.strokeStyle = "black"; 35 } 36 ctx.lineWidth = w; 37 ctx.beginPath(); 38 ctx.moveTo(x1, y1); 39 ctx.lineTo(x2, y2); 40 ctx.stroke(); 41 } 42 function drawClock() { 43 var c = document.getElementById("myCanvas"); 44 var ctx = c.getContext("2d"); 45 ctx.clearRect(0, 0, c.width, c.height); cX = 300; 48 var cY = 200; 49 var radius = 100; (var i = 0; i < 60; i++) { 53 circle(ctx, cX, cY, radius, i * 6 * Math.PI / 180, (i + 1) * 6 * Math.PI / 180, 1); 54 } 55 circle0(ctx, cX, cY, radius * 9 / 10, 0, 2 * Math.PI, true); (var i = 0; i < 12; i++) { 58 circle(ctx, cX, cY, radius, i * 30 * Math.PI / 180, (i + 1) * 30 * Math.PI / 180, 2); 59 } 60 circle0(ctx, cX, cY, radius * 8 / 10, 0, 2 * Math.PI, true); circle1(ctx, cX, cY, radius * 11 / 10, 0, 2 * Math.PI, 1); 64 ctx.save(); 65 ctx.fillStyle = "black"; 66 ctx.font = "10px Arial"; (var i = 0; i < 12; i++) { 69 var fX = cX + Math.cos((i + 1) * 5 * 6 * Math.PI / 180 - Math.PI / 2) * radius * 7.5 / 10; 70 var fY = cY + Math.sin((i + 1) * 5 * 6 * Math.PI / 180 - Math.PI / 2) * radius * 7.5 / 10; 71 ctx.fillText((i + 1), fX, fY); 72 } 73 var date = new Date(); 74 var second = date.getSeconds(); 75 var minute = date.getMinutes(); 76 var hour = date.getHours(); secondX = cX + Math.cos(second * 6 * Math.PI / 180 - Math.PI / 2) * radius * 9 / 10; 81 var secondY = cY + Math.sin(second * 6 * Math.PI / 180 - Math.PI / 2) * radius * 9 / 10; 82 var minuteX = cX + Math.cos(minute * 6 * Math.PI / 180 - Math.PI / 2) * radius * 8 / 10; 83 var minuteY = cY + Math.sin(minute * 6 * Math.PI / 180 - Math.PI / 2) * radius * 8 / 10; hourX = cX + Math.cos(hour * 30 * Math.PI / 180 + (minute * 6 * Math.PI / 180) / 12 - Math.PI / 2) * radius * 6.5 / 10; 86 var hourY = cY + Math.sin(hour * 30 * Math.PI / 180 + (minute * 6 * Math.PI / 180) / 12 - Math.PI / 2) * radius * 6.5 / 10; line(ctx, cX, cY, secondX, secondY, 1); line(ctx, cX, cY, minuteX, minuteY, 2); line(ctx, cX, cY, hourX, hourY, 3); 93 ctx.fillStyle = "black"; 94 ctx.font = "15px Arial"; 95 ctx.fillText("CurrentTime is : " + date.toLocaleString(), 150, 450); 96 ctx.save(); 97 } 98 window.onload = function () { setInterval(drawClock, 1000); 101 } 102 </script>
View Code