css实现圆周运动效果

在CSS中可以通过 @keyframes 动画transform 属性实现元素的圆周运动。以下是一个示例代码:

示例代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS圆周运动</title>
<style>
  body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background: #f4f4f4;
  }

  .orbit {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px dashed #aaa; /* 可选,显示圆的轨迹 */
    border-radius: 50%; /* 圆形轨道 */
  }

  .object {
    position: absolute;
    width: 20px;
    height: 20px;
    background: red;
    border-radius: 50%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    animation: circular-motion 4s linear infinite;
  }

  @keyframes circular-motion {
    0% {
      transform: translate(-50%, -50%) rotate(0deg) translateX(100px);
    }
    100% {
      transform: translate(-50%, -50%) rotate(360deg) translateX(100px);
    }
  }
</style>
</head>
<body>
  <div class="orbit">
    <div class="object"></div>
  </div>
</body>
</html>

代码解析

  1. 轨道 (.orbit):

    • 设置了一个圆形轨道,大小为 200px,使用 border-radius: 50% 使其变成一个圆形。
  2. 运动物体 (.object):

    • 起始位置在轨道顶部,通过 position: absolute 定位。
    • 使用 transform: translate(-50%, -50%) 确保其中心点对齐。
  3. 动画 (@keyframes circular-motion):

    • 利用 rotate 实现旋转运动,中心点是容器的中心。
    • translateX(100px) 确保元素始终距离圆心一定距离。
  4. 无缝循环:

    • 设置动画为 linear infinite,让物体匀速持续旋转。

你可以调整以下参数来修改效果:

  • 调整轨道大小:修改 .orbitwidthheight
  • 调整运动速度:更改 animation 的持续时间,如 4s
  • 改变运动距离:更改 translateX 的值。
相关推荐
mCell18 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip18 小时前
Node.js 子进程:child_process
前端·javascript
excel21 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript