【问题标题】:CSS Animation - Grow from center (Zoom from center dot to full container)CSS 动画 - 从中​​心增长(从中心点缩放到整个容器)
【发布时间】:2017-07-26 17:52:00
【问题描述】:

我正在开发一款游戏,我想为一些盒子制作动画。

我希望一个盒子从小开始然后向外增长,所有边缘同时增长,效果看起来像是从中心向外增长。

到目前为止我最好的动画如下:它根据需要增加盒子的高度和宽度,但从左侧和顶部开始。我希望它从一个中心点开始。

我查看了 W3 上的动画属性,似乎没有什么适合这艘船。

  .box_2_gen{
    
    animation-duration: 0.25s;
    animation-name: createBox;

    position: relative;

    background: #FFEDAD;

    border: black solid;
    border-width: 1px;
    border-radius: 15px;

    width: 98px;
    height: 98px;

    margin: 10px;

    float: left;
}



@keyframes createBox{
    from{
        height:0px;
        width: 0px;

    }
    to{
        height: 98px;
        width: 98px;
    }
}

编辑:我的问题可能看起来像另一个类似的问题,但我只是想知道如何只使用关键帧。

谢谢,

【问题讨论】:

标签: css animation css-transforms


【解决方案1】:

这是一个全尺寸示例。我在玩 Michael Coker 的 StackSnippet 时为自己创建了它——但我想我还是会分享的。

/*  Look Carefully: This is NOT jQuery  */
const $ = document.querySelector.bind(document);
$('button').addEventListener("click", function() {
  $('button').style.display = 'none';
  $('div').style.display = 'block';
});
/*  All You Need  */
p {
  position: absolute;
  top:0;
  left:0;
  margin:0;
  background: red;
  animation: createBox .5s;
  width: 100vw; height: 100vh;
}
@keyframes createBox {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}


/* Extras for this Demo */
body{margin:0;} /*  Required for StackSnippet Container  */
div{
  display:none;
  margin: 0;
  padding: 0;
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 100vh;
  max-height: 100vh;
  overflow: hidden;
}
p{
  display: grid;
  place-items: center;
}
aside{
  height: 50vh;
  display: grid;
  place-items: center;
}
button{
  padding: 30px;
  font-size: 2rem;
}
sup{
font-size: .9rem;
}
<div><p>Hit the Run Code Snippet button again to re-run</p></div>
<aside><button>Show Me<br><sup>(Best viewed "Full Page")</sup></button></aside>

【讨论】:

    【解决方案2】:

    您应该在动画中使用transform 以获得更好的性能和更多的控制。这样您就不必重复静态的px 值,并且可以使用transform-origin 来控制转换发生的位置。 scale() 默认会从中心缩放。

    div {
      background: red;
      animation: createBox .25s;
      width: 98px; height: 98px;
    }
    @keyframes createBox {
      from {
        transform: scale(0);
      }
      to {
        transform: scale(1);
      }
    }
    &lt;div&gt;&lt;/div&gt;

    【讨论】:

    • 太棒了,正是我想要的。不过,我可能一直在寻找错误的资源。是否还可以获得进一步阅读的链接?
    • 这是MDN page on transform。此外,this page 直接提到了transform 比动画位置和height / width 更好(关于“图层、合成、CPU 和GPU”)。
    猜你喜欢
    • 2019-12-28
    • 2019-01-29
    • 1970-01-01
    • 2019-05-19
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2013-03-29
    相关资源
    最近更新 更多