代码展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Document</title>
<style>
body {
background: #000;
}
* {
margin: 0;
padding: 0;
}
#clock {
margin: 100px 550px;
background: #000;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="clock">
您的浏览器不支持canvas
</canvas>
<script>
var oClock = document.getElementById("clock");
var clock = oClock.getContext('2d');
function drawClock() {
clock.clearRect(0, 0, 500, 500);
var time = new Date();
var sec = time.getSeconds();
var min = time.getMinutes();
var hour = time.getHours();
hour = hour + min / 60;
clock.strokeStyle = "#00f";
clock.lineWidth = 10;
clock.beginPath();
clock.arc(250, 250, 200, 0, 360);
clock.stroke();
clock.closePath();
for (let i = 1; i <= 12; i++) {
clock.save();
clock.lineWidth = 8;
clock.strokeStyle = "#fff";
clock.translate(250, 250);
clock.rotate(i * 30 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -170);
clock.lineTo(0, -195);
clock.closePath();
clock.stroke();
clock.restore();
}
for (let i = 1; i <= 60; i++) {
clock.save();
clock.lineWidth = 5;
clock.strokeStyle = "#0f0";
clock.translate(250, 250);
clock.rotate(i * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(0, -180);
clock.lineTo(0, -192);
clock.closePath();
clock.stroke();
clock.restore();
}
clock.save();
clock.translate(250, 250);
clock.rotate(hour * 30 * Math.PI / 180);
clock.beginPath();
clock.moveTo(-2, -90);
clock.lineTo(-5, 15);
clock.lineTo(5, 15);
clock.lineTo(2, -90);
clock.closePath();
clock.fillStyle = "#0ff"
clock.lineWidth = 3
clock.fill();
clock.strokeStyle = "purple";
clock.stroke();
clock.restore();
clock.lineWidth = 2
clock.save();
clock.translate(250, 250);
clock.rotate(min * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(-2, -135);
clock.lineTo(-5, 20);
clock.lineTo(5, 20);
clock.lineTo(2, -135);
clock.closePath();
clock.fillStyle = "#0ff"
clock.lineWidth = 3
clock.fill();
clock.strokeStyle = "purple";
clock.stroke();
clock.restore();
clock.save();
clock.translate(250, 250);
clock.rotate(sec * 6 * Math.PI / 180);
clock.beginPath();
clock.moveTo(-2, -160);
clock.lineTo(-3, 30);
clock.lineTo(3, 30);
clock.lineTo(2, -160);
clock.closePath();
clock.fillStyle = 'red';
clock.fill();
clock.strokeStyle = '#00f'
clock.stroke();
clock.beginPath();
clock.arc(0, -145, 3, 0, 360);
clock.closePath();
clock.lineWidth = 2;
clock.stroke();
clock.restore();
clock.beginPath();
clock.arc(250, 250, 5, 0, 360, false);
clock.strokeStyle = '#fff'
clock.lineWidth = 5
clock.stroke();
clock.closePath();
}
setInterval(drawClock, 1000)
</script>
</body>
</html>