參照Mozilla 官方教程,要在Canvas上畫動畫時鐘,思路很是有意思。javascript
把動畫看做是多個幀組成,定時每一個時間點在Canvas上畫一幀來實現動畫。而Mozilla 官方教程畫圖實現的思路有意思的地方在於,它喜歡在畫布上面作文章,正常的思路,若是要畫一條傾斜45度的直線,通常會先用數據計算拿到起始點與末點的座標,先定位到起點畫線到末點;如何在畫布上面作文章呢,它先把畫布旋轉45度,而後直接在中間畫一條豎線,再把畫布復原,這樣直線也跟着傾斜45度了。就按這思路定時在Canvas上畫點、線、面實現時鐘動畫。html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>canvas時鐘 - Coffeescript實現</title> <script id="others_zepto_10rc1" type="text/javascript" class="library" src="/js/sandbox/other/zepto.min.js"></script> <script id="others_coffeescript" type="text/javascript" class="library" src="/js/sandbox/other/coffee-script.js"></script> </head> <body> <canvas id="canvas"></canvas> <h2> Coffeescript 練習 </h2> <p> Canvas時鐘 - Coffeescript實現 </p> <p> 參照 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations">An animated clock</a> </p> </body> <script type="text/coffeescript"> clock = -> now = new Date() ctx = document.getElementById('canvas').getContext '2d' ctx.save() ctx.clearRect 0,0,150,150 ctx.translate 75,75 ctx.scale 0.4,0.4 ctx.rotate -Math.PI/2 ctx.strokeStyle = "black" ctx.fillStyle = "white" ctx.lineWidth = 8 ctx.lineCap = "round" #畫12個小時的標刻 ctx.save() for i in [0..11] ctx.beginPath() ctx.rotate Math.PI/6 ctx.moveTo 100,0 ctx.lineTo 120,0 ctx.stroke() ctx.restore() #畫60個分鐘的標刻 ctx.save() ctx.lineWidth = 5 for i in [0..59] if i%5 isnt 0 ctx.beginPath() ctx.moveTo 117,0 ctx.lineTo 120,0 ctx.stroke() ctx.rotate Math.PI/30 ctx.restore() sec = now.getSeconds() min = now.getMinutes() hr = now.getHours() hr = if hr >= 12 then hr-12 else hr ctx.fillStyle = "black" #畫時針 ctx.save() ctx.rotate hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec ctx.lineWidth = 14 ctx.beginPath() ctx.moveTo -20,0 ctx.lineTo 80,0 ctx.stroke() ctx.restore() #畫分針 ctx.save() ctx.rotate (Math.PI/30)*min + (Math.PI/1800)*sec ctx.lineWidth = 10 ctx.beginPath() ctx.moveTo -28,0 ctx.lineTo 112,0 ctx.stroke() ctx.restore() #畫秒針 ctx.save() ctx.rotate sec * Math.PI/30 ctx.strokeStyle = "#D40000" ctx.fillStyle = "#D40000" ctx.lineWidth = 6 ctx.beginPath() ctx.moveTo -30,0 ctx.lineTo 83,0 ctx.stroke() ctx.beginPath() ctx.arc 0,0,10,0,Math.PI*2,true ctx.fill() ctx.beginPath() ctx.arc 95,0,10,0,Math.PI*2,true ctx.stroke() ctx.fillStyle = "rgba(0,0,0,0)" ctx.arc 0,0,3,0,Math.PI*2,true ctx.fill() ctx.restore() #畫鐘的外圈 ctx.beginPath() ctx.lineWidth = 14 ctx.strokeStyle = '#325FA2' ctx.arc 0,0,142,0,Math.PI*2,true ctx.stroke() ctx.restore() window.requestAnimationFrame clock return #啓動程序 clock() </script> </html>
參考自 An animated clockjava