canvas 製作時鐘
阿新 • • 發佈:2018-12-13
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 { 38return 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。
本例還有很多要優化的地方,時間有限,目前先這樣吧。