时隔多年,现在亲手试试写一个动态时钟。其实也不难,现在完成了当年遗留下课后思考。代码贴上。
var ctx;
function init() {
var canvas = document.getElementById("clock");
if (canvas && canvas.getContext) {
ctx = canvas.getContext("2d");
draw();
line();
window.setInterval("draw()", 1000);
window.setInterval("line()", 1000);
}
}
function draw() {
var grad = ctx.createRadialGradient(200, 200, 90, 200, 200, 0);
grad.addColorStop(0, "#CCFFFF");
grad.addColorStop(1, "#FFCC99");
ctx.fillStyle = grad;
//内圆周
ctx.beginPath();
ctx.arc(200, 200, 90, 0, 2 * Math.PI, true);
ctx.fill();
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var x = 0;
var y = 0;
//H
ctx.lineWidth = 5;
x = 200 + Math.sin(h / 12 * 2 * Math.PI) * 50;
y = 200 - Math.cos(h / 12 * 2 * Math.PI) * 50;
ctx.fillStyle = "#000000";
ctx.moveTo(200, 200);
ctx.lineTo(x, y);
ctx.stroke();
//M
ctx.lineWidth = 4;
x = 200 + Math.sin(m / 60 * 2 * Math.PI) * 60;
y = 200 - Math.cos(m / 60 * 2 * Math.PI) * 60;
ctx.fillStyle = "#000000";
ctx.moveTo(200, 200);
ctx.lineTo(x, y);
ctx.stroke();
//S
ctx.lineWidth = 2;
x = 200 + Math.sin(s / 60 * 2 * Math.PI) * 80;
y = 200 - Math.cos(s / 60 * 2 * Math.PI) * 80;
ctx.fillStyle = "#000000";
ctx.moveTo(200, 200);
ctx.lineTo(x, y);
ctx.stroke();
}
function line() {
var x1;
var x2;
var y1;
var y2;
var w;
var t;
var tx;
var ty;
for (var i = 1; i <= 60; i++) {
x1 = 200 + Math.sin(i / 60 * 2 * Math.PI) * 90;
y1 = 200 - Math.cos(i / 60 * 2 * Math.PI) * 90;
tx = 200 + Math.sin(i / 60 * 2 * Math.PI) * 74 - 4;
ty = 200 - Math.cos(i / 60 * 2 * Math.PI) * 74 + 4;
if (i % 5 == 0) {
x2 = 200 + Math.sin(i / 60 * 2 * Math.PI) * 80;
y2 = 200 - Math.cos(i / 60 * 2 * Math.PI) * 80;
w = 2
t = i / 5;
} else {
x2 = 200 + Math.sin(i / 60 * 2 * Math.PI) * 85;
y2 = 200 - Math.cos(i / 60 * 2 * Math.PI) * 85;
w = 1;
t = "";
}
ctx.lineWidth = w;
ctx.strokeText(t, tx, ty);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
}
<body οnlοad="init()">
<canvas id="clock" width="400" height="400"></canvas>
</body>
嗯 就这么些了,希望可以帮到一些需要的人。