返回
Neumorphism 风格数字时钟:JavaScript 代码详解
前端
2024-01-08 22:28:58
## 简介
时钟是我们用来测量时间的装置。如果使用得当,时钟对于任何 UI 都是有用的元素。时钟可用于以时间为主要关注点的网站,例如,会议室预订系统或活动日程表。时钟还可以用作装饰元素,为您的网站或应用程序增添一点个性。
## Neumorphism 风格
Neumorphism 是一种流行的设计风格,以其柔和的阴影和凸起效果为特征。这种风格非常适合设计时钟,因为它可以使时钟看起来更加现代和时尚。Neumorphism 风格的时钟通常使用浅色背景和深色数字。数字通常具有凸起效果,这使得它们看起来像从背景中浮出。
## JavaScript 代码
下面是使用 JavaScript 设计 Neumorphism 风格数字时钟的代码:
```javascript
const canvas = document.getElementById("clock");
const ctx = canvas.getContext("2d");
// 时钟半径
const radius = 100;
// 时钟中心点
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
// 绘制时钟表盘
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "#ffffff";
ctx.fill();
// 绘制时钟刻度
for (let i = 0; i < 12; i++) {
const angle = i * Math.PI / 6;
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = "#000000";
ctx.fill();
}
// 绘制时钟指针
const hourHandLength = radius * 0.5;
const minuteHandLength = radius * 0.75;
const secondHandLength = radius * 0.9;
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const hourAngle = hours * Math.PI / 6 + minutes * Math.PI / 360;
const minuteAngle = minutes * Math.PI / 30 + seconds * Math.PI / 1800;
const secondAngle = seconds * Math.PI / 30;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(centerX + hourHandLength * Math.cos(hourAngle), centerY + hourHandLength * Math.sin(hourAngle));
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(centerX + minuteHandLength * Math.cos(minuteAngle), centerY + minuteHandLength * Math.sin(minuteAngle));
ctx.strokeStyle = "#000000";
ctx.lineWidth = 3;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(centerX + secondHandLength * Math.cos(secondAngle), centerY + secondHandLength * Math.sin(secondAngle));
ctx.strokeStyle = "#ff0000";
ctx.lineWidth = 1;
ctx.stroke();
// 每秒更新时钟
setInterval(() => {
date.setTime(date.getTime() + 1000);
hours = date.getHours();
minutes = date.getMinutes();
seconds = date.getSeconds();
hourAngle = hours * Math.PI / 6 + minutes * Math.PI / 360;
minuteAngle = minutes * Math.PI / 30 + seconds * Math.PI / 1800;
secondAngle = seconds * Math.PI / 30;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawClockFace();
drawClockHands();
}, 1000);
结语
以上就是使用 JavaScript 设计 Neumorphism 风格数字时钟的代码详解。希望本文对您有所帮助。如果您有任何问题,请随时留言。