效果如下
JavaScript 椭圆旋转
完整html代码如下
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><div class="roll-container"><div class="roll-item">1</div><div class="roll-item">2</div><div class="roll-item">3</div><div class="roll-item">4</div><div class="roll-item">5</div><div class="roll-item">6</div><div class="roll-item">7</div><div class="roll-item">8</div></div>
</body>
<script>const centerX = 1000 / 2; // 椭圆中心的X轴坐标const centerY = 600 / 2; // 椭圆中心的Y轴坐标const a = 400; // 长半轴const b = 200; // 短半轴const rollItemDoms = document.querySelectorAll('.roll-container .roll-item');const rollItemTotal = rollItemDoms.length;let angles = []; // 不同的起始角度for (let i = 0; i < rollItemTotal; i++){angles.push(Math.PI * 2 / rollItemTotal * i); // 2π / n * i}let stopRolling = false; // 停止旋转function roll(){!stopRolling && rollItemDoms.forEach((element, index) => {const angle = angles[index]; // 获取当前元素的角度const x = centerX + a * Math.cos(angle);const y = centerY + b * Math.sin(angle);element.style.left = x + 'px';element.style.top = y + 'px';const normalizedY = (y - centerY + b) / (2 * b);const maxScale = 1;const minScale = 0.3;const scale = (maxScale - minScale) * normalizedY + minScale;element.style.transform = `scale(${scale})`;const maxOpacity = 1;const minOpacity = 0.5;const opacity = (maxOpacity - minOpacity) * normalizedY + minOpacity;element.style.opacity = opacity;angles[index] += 0.01; // 控制角度增量,从而控制运动速度,增量的正负决定了顺/逆时针旋转})requestAnimationFrame(roll);}roll();document.querySelector('.roll-container').addEventListener('mouseenter', (event) => {stopRolling = true;})document.querySelector('.roll-container').addEventListener('mouseleave', (event) => {stopRolling = false;})
</script>
<style>.roll-container{width: 1000px;height: 600px;position: relative;margin: 100px auto 0;background: greenyellow;}.roll-item{width: 60px;height: 60px;border-radius: 50%;position: absolute;top: 0;left: 0;transform: translate(-50%, -50%);background: red;font-size: 30px;line-height: 60px;text-align: center;color: #ffffff;font-weight: 700;}
</style>
</html>