JavaScript实现椭圆旋转,类似星球

效果如下

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>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值