canvas 制作时钟
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 6 <title>菜鸟教程(runoob.com)</title> 7 </head> 8 <body> 9 10 <canvas id="myCanvas" width="200" height="200" style="border:1px solid #c3c3c3;"> 11 您的浏览器不支持 HTML5 canvas 标签。 12 </canvas> 13 <span id="mySpan"></span> 14 15 <script> 16 17 function getMX(deg, r) { 18 var tan = Math.abs(Math.tan(deg * Math.PI / 180)); 19 return r * tan / Math.sqrt((1 + tan * tan)); 20 } 21 22 function getY(x, r) { 23 return Math.sqrt(r * r - x * x) 24 } 25 26 function getRealX(dgree, x) { 27 if (dgree <= 180) { 28 return R + x; 29 } else { 30 return R - x; 31 } 32 } 33 34 function getRealY(dgree, y) { 35 if (dgree < 90 || dgree > 270) { 36 return R - y; 37 } else { 38 return R + y; 39 } 40 } 41 42 function drawText() { 43 ctx.strokeText("12", 100, 25); 44 ctx.strokeText("3", 185, 100); 45 ctx.strokeText("6", 100, 185); 46 ctx.strokeText("9", 15, 100); 47 ctx.textAlign="center"; 48 ctx.font="20px sans-serif "; 49 } 50 51 var c = document.getElementById("myCanvas"); 52 var ctx = c.getContext("2d"); 53 var R = 100; 54 55 //ctx.fillStyle = "#FF0000"; 56 57 // ctx.fillRect(0, 0, 150, 75); 58 59 function draw() { 60 ctx.clearRect(0, 0, 200, 200); 61 var date = new Date(); 62 var mr = 60; 63 var hr = 40; 64 var sr = 80; 65 var mDgree = date.getMinutes() * 6; 66 var mx = getMX(mDgree, mr); 67 var my = getY(mx, mr); 68 var hDgree = date.getHours() * 30 + date.getMinutes() / 60 * 30; 69 var hx = getMX(hDgree, hr); 70 var hy = getY(hx, hr); 71 72 var sDgree = date.getSeconds() * 6; 73 var sx = getMX(sDgree, sr); 74 var sy = getY(sx, sr); 75 76 mx = getRealX(mDgree, mx); 77 my = getRealY(mDgree, my); 78 hx = getRealX(hDgree, hx); 79 hy = getRealY(hDgree, hy); 80 sx = getRealX(sDgree, sx); 81 sy = getRealY(sDgree, sy); 82 83 ctx.beginPath(); 84 ctx.arc(R, R, R, 0, 2 * Math.PI); 85 ctx.stroke(); 86 87 ctx.moveTo(R, R); 88 ctx.lineTo(mx, my); 89 ctx.stroke(); 90 91 ctx.moveTo(R, R); 92 ctx.lineTo(hx, hy); 93 ctx.stroke(); 94 95 ctx.moveTo(R, R); 96 ctx.lineTo(sx, sy); 97 ctx.stroke(); 98 drawText(); 99 100 document.getElementById('mySpan').innerHTML = "seconds:" + date.getSeconds() + ", degree:" 101 + sDgree + ", sx:" + sx + ",sy:" + sy; 102 103 } 104 105 106 //draw(); 107 108 setInterval(draw, 1000); 109 110 111 </script> 112 113 </body> 114 </html>
这是用js + html + canvas 制作的一个时钟,适合学生,前端学习者参考学习,通过学习本例,能够对canvas 有一个较好的认识,为以后的学习打下坚实的基础。本人近期也在学习前端知识,欢迎一起学习交流。
主要用到的技术及api
Math, Date, setInterval, Canvas。
本例还有很多要优化的地方,时间有限,目前先这样吧。
posted on 2018-12-13 12:00 cococooder 阅读(…) 评论(…) 编辑 收藏