js写一个会动的指针时钟
时间: 2023-06-12 18:06:27 浏览: 114
以下是一个基于JavaScript实现的指针时钟动画:
```html
<!DOCTYPE html>
<html>
<head>
<title>指针时钟</title>
<style>
canvas {
background-color: #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// 获取画布和上下文
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 设置画布大小
canvas.width = 400;
canvas.height = 400;
// 设置钟表半径和中心坐标
var radius = canvas.width / 2 - 20;
var x = canvas.width / 2;
var y = canvas.height / 2;
// 绘制钟表外框
function drawClock() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#fff';
ctx.lineWidth = 5;
ctx.stroke();
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
}
// 绘制时针
function drawHour(hour, minute) {
var angle = (hour * 30 + minute * 0.5) * Math.PI / 180;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineWidth = 7;
ctx.lineCap = 'round';
ctx.lineTo(x + Math.sin(angle) * (radius * 0.5), y - Math.cos(angle) * (radius * 0.5));
ctx.stroke();
}
// 绘制分针
function drawMinute(minute) {
var angle = minute * 6 * Math.PI / 180;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.lineTo(x + Math.sin(angle) * (radius * 0.7), y - Math.cos(angle) * (radius * 0.7));
ctx.stroke();
}
// 绘制秒针
function drawSecond(second) {
var angle = second * 6 * Math.PI / 180;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.lineTo(x + Math.sin(angle) * (radius * 0.9), y - Math.cos(angle) * (radius * 0.9));
ctx.strokeStyle = '#f00';
ctx.stroke();
}
// 更新时间并绘制钟表
function draw() {
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawClock();
drawHour(hour, minute);
drawMinute(minute);
drawSecond(second);
requestAnimationFrame(draw);
}
// 开始绘制动画
draw();
</script>
</body>
</html>
```
该代码会绘制一个黑色的背景,白色的钟表圆框和红色的秒针。时针和分针的样式为白色,时针为粗细为7,分针为粗细为5,秒针为粗细为3。秒针每秒会转动一次,分针每分钟会转动一次,时针每小时会转动一次。
阅读全文