当前位置:首页 > JavaScript

js实现风车

2026-01-31 16:19:05JavaScript

使用CSS和JavaScript实现风车动画

通过CSS定义风车叶片样式,使用JavaScript控制旋转动画。以下是实现步骤:

js实现风车

创建HTML结构

<div class="windmill">
  <div class="blade"></div>
  <div class="blade"></div>
  <div class="blade"></div>
  <div class="blade"></div>
</div>

添加CSS样式

.windmill {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 50px auto;
}

.blade {
  position: absolute;
  width: 100px;
  height: 20px;
  background-color: #FF5722;
  top: 90px;
  left: 50px;
  transform-origin: 0 50%;
}

.blade:nth-child(1) { transform: rotate(0deg); }
.blade:nth-child(2) { transform: rotate(90deg); }
.blade:nth-child(3) { transform: rotate(180deg); }
.blade:nth-child(4) { transform: rotate(270deg); }

实现JavaScript动画

let rotation = 0;
const windmill = document.querySelector('.windmill');

function animate() {
  rotation += 2;
  if (rotation >= 360) rotation = 0;
  windmill.style.transform = `rotate(${rotation}deg)`;
  requestAnimationFrame(animate);
}

animate();

优化风车效果

添加中心点和风车支柱的样式:

js实现风车

.windmill::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  background: #333;
  border-radius: 50%;
  top: 90px;
  left: 90px;
}

.windmill::before {
  content: '';
  position: absolute;
  width: 10px;
  height: 150px;
  background: #795548;
  top: 200px;
  left: 95px;
}

控制动画速度

修改JavaScript代码调整旋转速度:

let rotation = 0;
const speed = 1; // 控制速度

function animate() {
  rotation += speed;
  windmill.style.transform = `rotate(${rotation}deg)`;
  requestAnimationFrame(animate);
}

响应式风车

添加鼠标悬停效果:

windmill.addEventListener('mouseenter', () => speed = 3);
windmill.addEventListener('mouseleave', () => speed = 1);

这个实现创建了一个四叶片风车,使用CSS transform属性进行旋转,通过requestAnimationFrame实现平滑动画。可以根据需要调整叶片数量、颜色和旋转速度。

标签: 风车js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback)…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEv…