本範例運用 HTML5 的 canvas 標籤搭配 JavaScript,在頁面上模擬顯示一個運行的時鐘。透過 setInterval 每隔一段時間清空畫布並重繪時針、分針、秒針與刻度,即可達到動態走時的效果。請使用支援 HTML5 的瀏覽器預覽。
點擊這裡查看效果:https:///keleyi/phtml/html5clock.htm
以下是完整程式碼,存成 html 檔即可查看效果:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>HTML5時鐘</title>
</head>
<body>
<div>
<h1>HTML5時鐘</h1>
<canvas id="canvas" width="200" height="200" style="border:1px solid #000;">提示您,請使用支持HTML5的瀏覽器,例如Chrome,IE9,IE10,Firefox等。</canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
if (ctx) {
var timerId;
var frameRate = 60;
function canvObject() {
this.x = 0; this.y = 0; this.rotation = 0;
this.borderWidth = 2; this.borderColor = '#000000';
this.fill = false; this.fillColor = '#ff0000';
this.update = function () {
if (!this.ctx) throw new Error('提示:您沒指定ctx對象。');
var ctx = this.ctx
ctx.save();
ctx.lineWidth = this.borderWidth;
ctx.strokeStyle = this.borderColor;
ctx.fillStyle = this.fillColor;
ctx.translate(this.x, this.y);
if (this.rotation) ctx.rotate(this.rotation * Math.PI / 180);
if (this.draw) this.draw(ctx);
if (this.fill) ctx.fill();
ctx.stroke();
ctx.restore();
}
};
function Line() {};
Line.prototype = new canvObject();
Line.prototype.start = [0, 0];
Line.prototype.end = [5, 5];
Line.prototype.draw = function (ctx) {
ctx.beginPath(); ctx.moveTo.apply(ctx, this.start); ctx.lineTo.apply(ctx, this.end); ctx.closePath();
};
function Circle() {};
Circle.prototype = new canvObject();
Circle.prototype.draw = function (ctx) {
ctx.beginPath(); ctx.arc(0, 0, this.radius, 0, 2 * Math.PI, true); ctx.closePath();
};
var circle = new Circle();
circle.ctx = ctx; circle.x = 100; circle.y = 100; circle.radius = 90; circle.fill = true; circle.borderWidth = 6; circle.fillColor = '#ffffff';
var hour = new Line(); hour.ctx = ctx; hour.x = 100; hour.y = 100; hour.borderWidth = 10; hour.start = [0, 20]; hour.end = [0, -50];
var minute = new Line(); minute.ctx = ctx; minute.x = 100; minute.y = 100; minute.borderWidth = 7; minute.start = [0, 20]; minute.end = [0, -70];
var seconds = new Line(); seconds.ctx = ctx; seconds.x = 100; seconds.y = 100; seconds.borderColor = "#ff0000"; seconds.borderWidth = 4; seconds.start = [0, 20]; seconds.end = [0, -80];
timerId = setInterval(function () {
ctx.clearRect(0, 0, 200, 200);
ctx.fillStyle = 'orange'; ctx.fillRect(0, 0, 200, 200);
circle.update();
hour.rotation = (new Date()).getHours() * 30; hour.update();
minute.rotation = (new Date()).getMinutes() * 6; minute.update();
seconds.rotation = (new Date()).getSeconds() * 6; seconds.update();
}, (1000 / frameRate) | 0);
} else { alert('提示:您的瀏覽器不支持HTML5無法預覽.'); }
</script>
</body>
</html>