js实现风车
实现风车动画的步骤
使用HTML和CSS创建风车的基本结构,通过JavaScript控制旋转动画。
HTML结构
<div class="windmill">
<div class="blades"></div>
<div class="tower"></div>
</div>
CSS样式
.windmill {
position: relative;
width: 200px;
height: 300px;
}
.blades {
width: 100px;
height: 100px;
background-color: #f5f5f5;
border-radius: 50%;
position: absolute;
top: 50px;
left: 50px;
transform-origin: center;
}
.tower {
width: 20px;
height: 200px;
background-color: #333;
position: absolute;
bottom: 0;
left: 90px;
}
JavaScript动画控制
const blades = document.querySelector('.blades');
let rotation = 0;
function rotateBlades() {
rotation += 2;
if (rotation >= 360) {
rotation = 0;
}
blades.style.transform = `rotate(${rotation}deg)`;
requestAnimationFrame(rotateBlades);
}
rotateBlades();
添加风车叶片细节
通过CSS伪元素为风车添加四个叶片。
.blades::before,
.blades::after,
.blades::first-child,
.blades::last-child {
content: '';
position: absolute;
width: 100px;
height: 20px;
background-color: #ff9800;
top: 40px;
left: 0;
}
.blades::before {
transform: rotate(0deg);
}
.blades::after {
transform: rotate(90deg);
}
.blades::first-child {
transform: rotate(45deg);
}
.blades::last-child {
transform: rotate(135deg);
}
控制动画速度
通过修改JavaScript代码中的旋转增量来控制风车转速。
let speed = 1; // 调整这个值改变转速
rotation += speed;
响应式风车设计
添加媒体查询使风车在不同屏幕尺寸下保持比例。
@media (max-width: 600px) {
.windmill {
width: 100px;
height: 150px;
}
.blades {
width: 50px;
height: 50px;
top: 25px;
left: 25px;
}
.tower {
width: 10px;
height: 100px;
left: 45px;
}
}
添加交互控制
通过事件监听器让用户控制风车启停。
const windmill = document.querySelector('.windmill');
let isRotating = true;
windmill.addEventListener('click', () => {
isRotating = !isRotating;
if (isRotating) {
rotateBlades();
}
});
修改旋转函数以响应停止状态:
function rotateBlades() {
if (!isRotating) return;
rotation += 2;
blades.style.transform = `rotate(${rotation}deg)`;
requestAnimationFrame(rotateBlades);
}






