You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于SVG动画实现潜艇SVG的波浪漂浮定位需求

我来帮你实现潜艇随波浪漂浮的动画效果!我们需要让潜艇和波浪的动画完全同步,同时保持它在波浪上方的垂直居中状态,下面是完整的解决方案:

完整实现代码

HTML部分

<div class="ocean">
  <img class="submarine" src="https://image.flaticon.com/icons/svg/447/447773.svg" alt="Submarine">
  <div class="wave"></div>
  <div class="wave"></div>
</div>

CSS部分

// best seen at 1500px or less
html, body { height: 100%; }
body { 
  background:radial-gradient(ellipse at center, rgba(255,254,234,1) 0%, rgba(255,254,234,1) 35%, #B7E8EB 100%); 
  overflow: hidden; 
}
.ocean { 
  height: 5%; 
  width:100%; 
  position:absolute; 
  bottom:0; 
  left:0; 
  background: #015871; 
}
.wave { 
  background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/85486/wave.svg) repeat-x; 
  position: absolute; 
  top: -198px; 
  width: 6400px; 
  height: 198px; 
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) infinite; 
  transform: translate3d(0, 0, 0); 
}
.wave:nth-of-type(2) { 
  top: -175px; 
  animation: wave 7s cubic-bezier( 0.36, 0.45, 0.63, 0.53) -.125s infinite, swell 7s ease -1.25s infinite; 
  opacity: 1; 
}
.submarine {
  position: absolute;
  bottom: 120px; /* 可根据需求调整,确保潜艇在波浪上方 */
  left: 50%;
  transform: translateX(-50%);
  width: 80px; /* 调整潜艇显示尺寸 */
  z-index: 10; /* 保证潜艇不会被波浪遮挡 */
  animation: move-horizontal 7s cubic-bezier(0.36, 0.45, 0.63, 0.53) infinite,
             move-vertical 7s ease -1.25s infinite;
}

@keyframes wave { 
  0% { margin-left: 0; } 
  100% { margin-left: -1600px; } 
}
@keyframes swell { 
  0%, 100% { transform: translate3d(0,-25px,0); } 
  50% { transform: translate3d(0,5px,0); } 
}
@keyframes move-horizontal {
  0% {
    left: 100%; /* 潜艇从屏幕右侧进入 */
  }
  100% {
    left: -10%; /* 潜艇从屏幕左侧移出,形成循环 */
  }
}
@keyframes move-vertical {
  0%, 100% {
    transform: translateX(-50%) translateY(-15px);
  }
  50% {
    transform: translateX(-50%) translateY(5px);
  }
}

关键实现细节说明

  • 潜艇元素添加:用<img>标签引入潜艇SVG,方便控制尺寸和定位,同时设置z-index确保它在波浪图层上方。
  • 同步水平移动:潜艇的move-horizontal动画和波浪的wave动画使用完全一致的时长(7s)和缓动曲线,保证潜艇移动节奏和波浪滚动完全匹配,视觉上像是跟着波浪前进。
  • 模拟波浪起伏:move-vertical动画参考波浪的swell动画参数,设置相同的时长和时间偏移,让潜艇随波浪的上下起伏同步晃动,同时通过translateX(-50%)始终保持水平居中状态。
  • 可自定义调整:你可以修改潜艇的width、bottom值,以及动画中的位移数值,来适配不同的视觉需求。

内容的提问来源于stack exchange,提问作者Cloud9c

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:53:57