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 的值。
相关推荐
FinClip3 分钟前
凡泰极客亮相香港金融科技周,AI助力全球企业构建超级应用
前端
阿四22 分钟前
【Nextjs】为什么server action中在try/catch内写redirect操作会跳转失败?
前端·next.js
申阳25 分钟前
Day 6:04. 基于Nuxt开发博客项目-LOGO生成以及ICON图标引入
前端·后端·程序员
中国lanwp37 分钟前
npm中@your-company:registry 和 registry 的区别
前端·npm·node.js
Bacon39 分钟前
Electron 应用商店:开箱即用工具集成方案
前端·github
行走的陀螺仪40 分钟前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3
冴羽43 分钟前
JavaScript 异步循环踩坑指南
前端·javascript·node.js
jump68044 分钟前
commonjs 和 ES Module
前端
旧曲重听11 小时前
前端需要掌握多少Node.js?
前端·node.js
Mr.Jessy1 小时前
Web APIs 学习第四天:DOM事件进阶
开发语言·前端·javascript·学习·ecmascript