使用css3实现小车行驶的动画效果

<!DOCTYPE html>
<html>
<head>
<title>Car Animation</title>
<style>
body {
  background-color: #f0f0f0;
}

.container {
  width: 800px;
  height: 200px;
  margin: 50px auto;
  border: 1px solid #ccc;
  position: relative;
  overflow: hidden; /* 隐藏溢出部分 */
}

.car {
  width: 100px;
  height: 50px;
  background-color: red;
  position: absolute;
  left: -100px; /* 初始位置在容器外 */
  bottom: 20px;
  border-radius: 5px;
  animation: drive 5s linear infinite; /* 应用动画 */
}

.wheel {
  width: 20px;
  height: 20px;
  background-color: black;
  border-radius: 50%;
  position: absolute;
  bottom: 5px;
  animation: rotate 1s linear infinite; /* 车轮旋转动画 */
}

.wheel.front {
  left: 10px;
}

.wheel.back {
  right: 10px;
}


@keyframes drive {
  0% {
    left: -100px; /* 从左侧进入 */
  }
  100% {
    left: 900px; /* 移动到右侧,超出容器 */
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
</head>
<body>

<div class="container">
  <div class="car">
    <div class="wheel front"></div>
    <div class="wheel back"></div>
  </div>
</div>

</body>
</html>

代码解释:

  • HTML 结构: 创建一个 container 作为道路,car 作为小车,wheel 作为车轮。
  • CSS 样式:
    • container: 设置宽度、高度、边框,overflow: hidden; 隐藏超出容器的部分,使小车消失在右侧。
    • car: 设置小车的样式,left: -100px; 初始位置在容器左侧外,animation: drive 5s linear infinite; 应用 drive 动画,使其移动。
    • wheel: 设置车轮样式,animation: rotate 1s linear infinite; 应用 rotate 动画,使其旋转。
  • @keyframes drive: 定义小车移动的动画,从左侧 -100px 移动到右侧 900pxlinear 表示匀速运动,infinite 表示无限循环。
  • @keyframes rotate: 定义车轮旋转动画,从 0deg 旋转到 360deg,实现车轮转动效果。

改进和扩展:

  • 更逼真的车身: 可以使用更复杂的 CSS 或图片来创建更逼真的车身。
  • 背景移动: 可以让背景也移动,模拟小车在行驶的效果。
  • 控制速度: 可以使用 JavaScript 来控制小车的速度和方向。
  • 添加其他元素: 可以添加道路、建筑物、树木等元素,使场景更丰富。

This example provides a basic car animation. You can modify and enhance it further to create more complex and realistic animations.

posted @   王铁柱6  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
点击右上角即可分享
微信分享提示