<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D方块柱形图起伏动画特效</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const bars = [];
const barCount = 20;
const maxHeight = 200;
const minHeight = 50;
const barWidth = 30;
const spacing = 10;
// 初始化柱子
for (let i = 0; i < barCount; i++) {
bars.push({
x: i * (barWidth + spacing) + 100,
y: canvas.height / 2,
width: barWidth,
height: minHeight + Math.random() * (maxHeight - minHeight),
targetHeight: minHeight + Math.random() * (maxHeight - minHeight),
color: `hsl(${Math.random() * 360}, 100%, 50%)`,
speed: 0.05 + Math.random() * 0.05
});
}
function draw3DBar(x, y, width, height, color) {
// 3D效果
const depth = 10;
// 正面
ctx.fillStyle = color;
ctx.fillRect(x, y - height, width, height);
// 顶部
ctx.fillStyle = shadeColor(color, -20);
ctx.beginPath();
ctx.moveTo(x, y - height);
ctx.lineTo(x + depth, y - height - depth);
ctx.lineTo(x + width + depth, y - height - depth);
ctx.lineTo(x + width, y - height);
ctx.closePath();
ctx.fill();
// 侧面
ctx.fillStyle = shadeColor(color, -40);
ctx.beginPath();
ctx.moveTo(x + width, y - height);
ctx.lineTo(x + width + depth, y - height - depth);
ctx.lineTo(x + width + depth, y - depth);
ctx.lineTo(x + width, y);
ctx.closePath();
ctx.fill();
}
function shadeColor(color, percent) {
let R = parseInt(color.substring(4, color.indexOf(",")), 10);
let G = parseInt(color.substring(color.indexOf(",") + 2, color.lastIndexOf(",")), 10);
let B = parseInt(color.substring(color.lastIndexOf(",") + 2, color.indexOf(")")), 10);
R = parseInt(R * (100 + percent) / 100);
G = parseInt(G * (100 + percent) / 100);
B = parseInt(B * (100 + percent) / 100);
R = (R < 255) ? R : 255;
G = (G < 255) ? G : 255;
B = (B < 255) ? B : 255;
return `rgb(${R}, ${G}, ${B})`;
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新柱子高度
bars.forEach(bar => {
bar.height += (bar.targetHeight - bar.height) * bar.speed;
if (Math.abs(bar.targetHeight - bar.height) < 1) {
bar.targetHeight = minHeight + Math.random() * (maxHeight - minHeight);
}
draw3DBar(bar.x, bar.y, bar.width, bar.height, bar.color);
});
requestAnimationFrame(animate);
}
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>