js 实现沙漏
实现沙漏的 JavaScript 方法
使用 JavaScript 实现沙漏效果可以通过 CSS 动画和 JavaScript 定时器结合完成。以下是一个简单的实现方法。
创建 HTML 结构
<div class="hourglass">
<div class="top"></div>
<div class="bottom"></div>
</div>
添加 CSS 样式
.hourglass {
width: 100px;
height: 200px;
position: relative;
}
.top, .bottom {
width: 100%;
height: 50%;
background-color: #f0f0f0;
position: absolute;
}
.top {
top: 0;
border-bottom: 2px solid #333;
}
.bottom {
bottom: 0;
border-top: 2px solid #333;
}
JavaScript 控制动画
const topPart = document.querySelector('.top');
const bottomPart = document.querySelector('.bottom');
let sandHeight = 0;
function animateHourglass() {
sandHeight += 1;
if (sandHeight <= 100) {
topPart.style.height = `${50 - sandHeight / 2}%`;
bottomPart.style.height = `${50 + sandHeight / 2}%`;
requestAnimationFrame(animateHourglass);
}
}
animateHourglass();
使用 Canvas 绘制沙漏
如果需要更复杂的沙漏效果,可以使用 Canvas 绘制。
HTML 设置
<canvas id="hourglass" width="200" height="400"></canvas>
JavaScript 绘制逻辑
const canvas = document.getElementById('hourglass');
const ctx = canvas.getContext('2d');
let sandLevel = 0;
function drawHourglass() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制沙漏框架
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 200);
ctx.lineTo(150, 350);
ctx.lineTo(50, 350);
ctx.lineTo(100, 200);
ctx.closePath();
ctx.stroke();
// 绘制上部沙子
ctx.fillStyle = '#d4a017';
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 200 - sandLevel);
ctx.lineTo(50, 50);
ctx.fill();
// 绘制下部沙子
ctx.beginPath();
ctx.moveTo(100, 200 + sandLevel);
ctx.lineTo(150, 350);
ctx.lineTo(50, 350);
ctx.lineTo(100, 200 + sandLevel);
ctx.fill();
sandLevel += 1;
if (sandLevel <= 200) {
requestAnimationFrame(drawHourglass);
}
}
drawHourglass();
使用 CSS 动画实现沙漏
纯 CSS 也可以实现沙漏效果,但交互性较弱。

HTML 结构
<div class="hourglass">
<div class="sand-top"></div>
<div class="sand-bottom"></div>
</div>
CSS 动画
.hourglass {
width: 100px;
height: 200px;
position: relative;
border: 2px solid #333;
}
.sand-top, .sand-bottom {
width: 100%;
position: absolute;
background-color: #d4a017;
}
.sand-top {
top: 0;
height: 100%;
animation: drain 5s linear forwards;
}
.sand-bottom {
bottom: 0;
height: 0%;
animation: fill 5s linear forwards;
}
@keyframes drain {
to { height: 0%; }
}
@keyframes fill {
to { height: 100%; }
}
以上方法可以根据需求选择适合的实现方式。CSS 方法简单但功能有限,Canvas 方法灵活但代码量较大。






