HTML5圓形時鐘是一款非常實用的工具,它可以幫助我們實現在網頁上展示實時時間的功能。下面是一個簡單的HTML5圓形時鐘代碼示例:
<canvas id="clock" width="200" height="200"></canvas> <script> var canvas = document.getElementById("clock"); var context = canvas.getContext("2d"); var radius = canvas.height / 2; context.translate(radius, radius); radius = radius * 0.90; setInterval(drawClock, 1000); function drawClock() { drawFace(context, radius); drawNumbers(context, radius); drawTime(context, radius); } function drawFace(context, radius) { var grad; context.beginPath(); context.arc(0, 0, radius, 0, 2 * Math.PI); context.fillStyle = "#3f3f3f"; context.fill(); grad = context.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05); grad.addColorStop(0, "#fff"); grad.addColorStop(0.5, "#3f3f3f"); grad.addColorStop(1, "#fff"); context.strokeStyle = grad; context.lineWidth = radius * 0.1; context.stroke(); context.beginPath(); context.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); context.fillStyle = "#fff"; context.fill(); } function drawNumbers(context, radius) { var ang; var num; context.font = radius * 0.15 + "px arial"; context.textBaseline = "middle"; context.textAlign = "center"; for (num = 1; num <= 12; num++) { ang = num * Math.PI / 6; context.rotate(ang); context.translate(0, -radius * 0.85); context.rotate(-ang); context.fillText(num.toString(), 0, 0); context.rotate(ang); context.translate(0, radius * 0.85); context.rotate(-ang); } } function drawTime(context, radius) { var now = new Date(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); //hour hour = hour % 12; hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60)) + (second * Math.PI / (360 * 60)); drawHand(context, hour, radius * 0.5, radius * 0.07); //minute minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60)); drawHand(context, minute, radius * 0.8, radius * 0.07); // second second = (second * Math.PI / 30); drawHand(context, second, radius * 0.9, radius * 0.02); } function drawHand(context, pos, length, width) { context.beginPath(); context.lineWidth = width; context.lineCap = "round"; context.moveTo(0, 0); context.rotate(pos); context.lineTo(0, -length); context.stroke(); context.rotate(-pos); } </script>
上面的代碼使用了canvas元素來繪制圓形時鐘,其中包括繪制時鐘的各個部分,如表盤、時、分、秒針等。通過調用drawClock函數,每秒鐘更新一次時鐘的時間,從而實現動態展示實時時間的功能。
上一篇一個css中加兩個圖片
下一篇html5圓角虛線框代碼