<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> canvas 钟表效果 </title>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
display: block;
margin: 0 auto;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas width="400" height="400" id="canvas"></canvas>
</body>
</html>
<script>
/** @type {HTMLCanvasElement} **/
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
//创建一个钟表类
class Clock {
// 绘制表盘
drawDial() {
ctx.save();
ctx.beginPath();
ctx.arc(200, 200, 200, 0, 2 * Math.PI);
let gradient = ctx.createLinearGradient(0, 0, 400, 400);
gradient.addColorStop(0, '#f00');
gradient.addColorStop(0.5, '#fff');
gradient.addColorStop(1, '#0f0');
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
ctx.restore();
//绘制内部小表盘
ctx.save();
ctx.beginPath();
ctx.arc(200, 200, 180, 0, 2 * Math.PI);
// 添加阴影
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 40;
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.fillStyle = '#fff';
ctx.fill();
ctx.closePath();
ctx.restore();
}
// 绘制刻度
drawScale() {
ctx.save();
ctx.translate(200, 200)
for (let i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate(Math.PI / 6);
ctx.moveTo(0, -180);
ctx.lineTo(0, -160);
ctx.lineWidth = 5;
ctx.strokeStyle = '#333';
ctx.stroke();
}
//绘制数字
ctx.font = '20px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let i = 1; i <= 12; i++) {
ctx.fillText(i, Math.cos((Math.PI / 6) * (i - 3)) * 140, Math.sin((Math.PI / 6) * (i - 3)) * 140);
}
ctx.closePath();
ctx.restore();
}
// 绘制指针
drawPointer() {
ctx.save();
ctx.translate(200, 200);
//获取当前时间
let now = new Date();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
// 0度在3点钟方向,需要先旋转到12点钟方向
ctx.rotate(-Math.PI / 2);
//绘制秒针
ctx.save();
//旋转的度数
ctx.rotate( Math.PI/180 * (second * 6));
ctx.beginPath();
ctx.moveTo(-60, 0);
ctx.lineTo(120, 0);
ctx.lineWidth = 2;
ctx.strokeStyle = '#f00';
ctx.stroke();
ctx.closePath();
ctx.restore();
//绘制分针
ctx.save();
//旋转的度数
ctx.rotate(Math.PI / 180 * (minute * 6));
ctx.beginPath();
ctx.moveTo(-40, 0);
ctx.lineTo(110, 0);
ctx.lineWidth = 5;
ctx.strokeStyle = '#0f0';
ctx.stroke();
ctx.closePath();
ctx.restore();
//绘制时针
ctx.save();
//旋转的度数
ctx.rotate(Math.PI / 180 * (hour *30 + minute * 0.5 + second/120));
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(80, 0);
ctx.lineWidth = 10;
ctx.strokeStyle = '#00f';
ctx.stroke();
ctx.closePath();
ctx.restore();
// 绘制中心圆点
ctx.save();
ctx.beginPath();
ctx.arc(0, 0, 10, 0, 2 * Math.PI);
ctx.fillStyle = '#f00';
ctx.fill();
ctx.closePath();
ctx.restore();
ctx.restore();
}
}
let clock = new Clock();
// 绘制动画
function draw() {
//清除画布
ctx.clearRect(0, 0, 400, 400);
// 绘制表盘
clock.drawDial();
// 绘制刻度
clock.drawScale();
// 绘制指针
clock.drawPointer();
requestAnimationFrame(draw);
}
draw();
</script>
03-30
165
09-26
443