"flip"动画

#javascript #animation

flip动画

  1. first: 元素在动画中的初始状态
  2. last: 元素的动画的结束状态
  3. invert: 计算first和last状态的差值,然后设置相应的属性(transform, opacity等),使元素在初始状态。
  4. play: 触发整个动画

一个例子🌰

<head>
  <style media="screen">
    body {
    }

    .container {
      width: 100%;
      height: 100%;
      margin: 0 auto;
      background: #BBDEFB;
      position: relative;
    }

    .circle {
      width: 100px;
      height: 100px;
      border-radius: 100%;
      background-color: #E1BEE7;
      position: absolute;
      top: 10px;
      left: 10px;
    }

    .circle-end {
      top: auto;
      left: auto;
      bottom: 10px;
      right: 10px;
    }

  </style>
</head>

<body>
  <button type="button" name="button" onclick="doAnimate()">Animate</button>
  <div class="container">
    <div class="circle">
    </div>
  </div>
  <script type="text/javascript">
  function doAnimate() {
    var node = document.getElementsByClassName('circle')[0]

    //计算初始属性
    var first = node.getBoundingClientRect()
    node.classList.add('circle-end')
    //计算结束属性
    var last = node.getBoundingClientRect()

    //invert
    var invertX = first.left - last.left
    var invertY = first.top - last.top

    node.style.transform = 'translate(' + invertX + 'px,' + invertY + 'px)'
    node.style.transition = 'transform 0s'

    requestAnimationFrame(function(node) {
      return function() {

        //触发动画
        node.style.transition = 'all 1s';
        node.style.transform  = '';
        console.log(node)
      }
    }(node))
  }

  </script>
</body>

requestAnimationFrame函数

requestAnimationFrame函数主要告诉浏览器在重绘每一帧动画时,可以运行用户定义的代码,可以进行相应的计算等等。

参考资料

  1. Animating the Unanimatable.
  2. FLIP Your Animations