首页 > 解决方案 > 动画两个圆圈以恰好在中间相遇

问题描述

所以我的目标是让两个圆圈从屏幕的两侧相遇并在中间相遇以执行动画的后半部分(缩放和不透明度变化)。

但是通过设置初始关键帧并最后使用 vw 他们不会在中间相遇 - 因为 vw 值是相对于 div 的左侧而不是中心(我使用 vw 因为我需要它来响应)。所以,会发生什么是圆的左侧在中心相遇。

有谁知道只使用 css 的简单修复?我对编码很陌生,所以如果答案很明显,我很抱歉。

这是我的代码:

@keyframes left {
  0% {
    transform: translate3d(0vw, 50%, 0) scale3d(1, 1, 1);
    opacity: 50%;
    animation-timing-function: ease-in;
  }
  60% {
    transform: translate3d(50vw, 50%, 0) scale3d(1, 1, 1);
    opacity: 50%;
    animation-timing-function: ease-out;
  }
  100% {
    transform: translate3d(50vw, 50%, 0) scale3d(2, 2, 1);
    opacity: 0%;
    animation-timing-function: ease-out;
  }
}

@keyframes right {
  0% {
    transform: translate3d(100vw, 50%, 0) scale3d(1, 1, 1);
    opacity: 50%;
    animation-timing-function: ease-in;
  }
  60% {
    transform: translate3d(50vw, 50%, 0) scale3d(1, 1, 1);
    opacity: 50%;
    animation-timing-function: ease-out;
  }
  100% {
    transform: translate3d(50vw, 50%, 0) scale3d(2, 2, 1);
    opacity: 0%;
    animation-timing-function: ease-out;
  }
}

.circleleft {
  overflow: hidden;
  position: absolute;
  background: white;
  border-radius: 50%;
  width: 500px;
  height: 500px;
  animation: left 2s;
  animation-fill-mode: forwards;
}

.circleright {
  overflow: hidden;
  position: absolute;
  background: white;
  border-radius: 50%;
  width: 500px;
  height: 500px;
  animation: right 2s;
  animation-fill-mode: forwards;
}
<div style="width:100vw; height:100vh; background-color:#87827E">
  <div class="circleleft"></div>
  <div class="circleright"></div>
</div>

您也可以在这里看到它的使用情况:https ://ruairimadine.co.uk/sudoroux

标签: htmlcsscss-animationskeyframetranslate3d

解决方案


一个技巧是最初将两个圆圈定位在中心,动画/平移将使它们从左侧或右侧偏移。

我优化了代码以仅使用伪元素并使其更易于理解:

body {
  margin: 0;
  height: 100vh;
  background-color: #87827E;  
  overflow: hidden;
  position:relative;
}
body::before,
body::after{
  content:"";
  position: absolute;
  top: calc(50% - 25vmin);
  left:calc(50% - 25vmin);
  background: white;
  opacity: 50%;
  border-radius: 50%;
  width: 50vmin;
  height: 50vmin;
  animation: move 2s forwards;
}
/* 50vw : half the screen width | 25vmin half the circle width*/
body::before { transform:translateX(calc( 50vw + 25vmin)); }
body::after  { transform:translateX(calc(-50vw - 25vmin)); }

@keyframes move {
  60% {
    transform: translateX(0) scale(1);
    opacity: 50%;
  }
  100% {
    transform: translateX(0) scale(2);
    opacity: 0%;
  }
}


推荐阅读