使用HTML5制作时钟
<script><br> var Clock = function (canvas, options) {<br> this.canvas = canvas;<br> this.ctx = this.canvas.getContext("2d");<br> this.options = options;<br> };</p>
<p> Clock.prototype = {<br> constructor: Clock,<br> drawCircle: function () {<br> var ctx = this.ctx;<br> ctx.strokeStyle = "black";<br> ctx.arc(this.canvas.width / 2, this.canvas.height / 2, 50, 0, 2 * Math.PI, false);<br> ctx.stroke();<br> },<br> drawNum: function () {<br> var ctx = this.ctx;<br> var angle = Math.PI * 2 / 12;<br> for (var i = 1; i <= 12; i = 1) {<br /> ctx.font = "20px Georgia";<br /> ctx.textAlign = "center";<br /> ctx.textBaseline = 'middle';<br /> ctx.fillText(String(i), this.canvas.width / 2 Math.cos(3 *Math.PI / 2 angle * i) * 40, this.canvas.height / 2 Math.sin(3 * Math.PI / 2 angle * i) * 40);<br /> }<br /> },<br /> drawPointer: function () {<br /> var ctx = this.ctx;<br /> var that = this;<br /> var date, hour, minute, second;<br /> date = new Date();<br /> hour = date.getHours();<br /> if (hour > 12) {<br> hour = hour % 12;<br> }<br> minute = date.getMinutes();<br> second = date.getSeconds();</p>
<p> var b = minute * Math.PI / 30;<br> var c = second * Math.PI / 30;<br> var a = hour * Math.PI / 6 Math.PI / 6 * minute / 60;<br> var minuteAngle = Math.PI * 2 / 3600;<br> var secondAngle = Math.PI * 2 / 60;<br> var hourAngle = Math.PI * 2 / 12 / 3600;</p>
<p> ctx.beginPath();<br> ctx.save();<br> ctx.translate(that.canvas.width / 2, that.canvas.height / 2);<br> ctx.arc(0, 0, 3, 0, 2 * Math.PI, false);<br> ctx.fill();<br> ctx.closePath();<br> ctx.beginPath();<br> a = hourAngle;<br> ctx.rotate(a);<br> ctx.fillRect(-2, -22, 4, 30);<br> ctx.closePath();<br> ctx.beginPath();<br> b = minuteAngle;<br> ctx.rotate(b - a);<br> ctx.fillRect(-1.5, -26, 3, 35);<br> ctx.closePath();<br> ctx.beginPath();<br> c = secondAngle;<br> ctx.rotate(c - b);<br> ctx.fillRect(-1, -30, 2, 40);<br> ctx.closePath();<br> ctx.restore();<br> },<br> rePaint: function () {<br> this.drawPointer();<br> this.drawCircle();<br> this.drawNum();<br> },<br> tik: function () {<br> var that = this;<br> var ctx = this.ctx;<br> this.rePaint();<br> window.timer = setInterval(function () {<br> ctx.clearRect(0, 0, that.canvas.width, that.canvas.height);<br> that.rePaint();<br> }, 1000);<br> }<br> };</p>
<p> var options;<br> var clock = new Clock(document.getElementById("canvas"), options);<br> clock.tik();<br> </script>