最近试着用canvas元素的2d绘图函数做了一个弧线形的时钟。
我也没啥好说的,直接上代码:
<div id="myclock"></div> <script> createClock("#myclock", 0, 0.5); function createClock(selector, n, p_r) { var weeks = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var p_b = 0.09; var p_d = 0.4; var n_c = "rgba(255,150,0,1)"; var canv = document.createElement("canvas"); var c = canv.getContext("2d"); var p = document.querySelectorAll(selector)[n]; p.appendChild(canv); canv.style.display = "block"; var r, b, l; function resizing() { r = p_r * p.clientWidth; canv.width = canv.height = 2 * r; b = p_b * r; l = r - (3 + 2 * p_d) * b; c.lineWidth = b; c.lineCap = "round"; c.strokeStyle = n_c; } resizing(); window.addEventListener("resize", resizing); function fraps() { var t = new Date(); var ds = t.getFullYear() + '/' + ct(t.getMonth() + 1) + '/' + ct(t.getDate()); var ws = weeks[t.getDay()]; var hs = ct(t.getHours()) + ':' + ct(t.getMinutes()); var ss = ct(t.getSeconds()); var sn = t.getSeconds() + 0.001 * t.getMilliseconds(); var mn = t.getMinutes() + sn / 60; var hn = t.getHours() + mn / 60; if (hn > 12) hn -= 12; c.clearRect(0, 0, 2 * r, 2 * r); c.fillStyle = 'black'; c.font = 0.65 * l + "px Arial bold"; c.fillText(hs, r - 0.845 * l, r + 0.247 * l); c.fillStyle = 'red'; c.font = 0.27 * l + "px Arial bold"; c.fillText(ds, r - 0.75 * l, r - 0.3 * l); c.font = 0.35 * l + "px Arial bold"; c.fillText(ws, r - 0.7 * l, r + 0.6 * l); c.fillStyle = 'aqua'; c.font = 0.57 * l + "px Arial bold"; c.fillText(ss, r, r + 1.3 * 0.57 * l); c.beginPath(); c.arc(r, r, r - 0.5 * b, -0.5 * Math.PI, (sn / 30 - 0.5) * Math.PI); c.stroke(); c.beginPath(); c.arc(r, r, r - (1.5 + p_d) * b, -0.5 * Math.PI, (mn / 30 - 0.5) * Math.PI); c.stroke(); c.beginPath(); c.arc(r, r, r - (2.5 + 2 * p_d) * b, -0.5 * Math.PI, (hn / 6 - 0.5) * Math.PI); c.stroke(); } function ct(i) { if (i < 10) i = "0" + i; return i; } setInterval(fraps, 40); } </script>