css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="ctn">
  <button id="linear-btn">线性动画</button></button>&emsp;
  <button id="collision-btn">碰撞动画</button></button>&emsp;
  <button id="bezier-btn">贝塞尔曲线动画</button></button>
</div>

<div id="box"></div>
            
          
!
            
              #ctn {
  text-align: center;
  margin: 30px;
}

#box {
  @d: 50px;
  width: @d;
  height: @d;
  position: fixed;
  background: linear-gradient(to bottom, #bb96f5 0%,#39acff 51%,#3eeafe 100%);
  border-radius: 10px;
  top: 100px;
}
            
          
!
            
              function getBezierCurve (...args: number[][]): (x: number) => number {
  if (args.length > 13)
    throw new Error('最多允许13个控制点');

  let points = [[0, 0], ...args, [1, 1]];

  let l = points.length,
    segments = 500,
    i = segments + 1, // n条线段总共n + 1个点
    xlist = Array(i),
    ylist = Array(i)

  // 阶乘, 无需考虑大数, 限制控制点个数即可
  const factorial = cached(function factorial (n: number): number {
    let res = 1;
    for (let i = 1; i <= n; i++)
      res *= i;
    return res;
  });

  // 组合数
  const combinatorial = cached(function combinatorial (n: number, m: number): number {
    if (m > n / 2) m = n - m;
    if (m === 0) return 1;
    if (m === 1) return n;
    if (m === 2) return n * (n - 1) / 2;
    if (m === 3) return n * (n - 1) * (n - 2) / 6;

    let i = n, j = m, res = 1;
    while (j--)
      res *= i--;
    return res / factorial(m);
  });

  while (i--)
    setBezierPoint(i);

  return function bezier (x: number): number {
    if (points.length === 2) return x;

    let i = getMaxIndex(x);

    if (i < 0) return ylist[0];
    if (i >= segments) return ylist[segments];

    let from = ylist[i], to = ylist[i + 1];

    return from + (to - from) * (x - xlist[i]);
  }

  // 二分查找x在 xlist例如[0, .02, .09, .22, ..., .99] 中哪个位置
  // 返回小于等于x的最大数的index
  function getMaxIndex (x: number): number {
    const len = xlist.length;
    let left = 0, right = len - 1;
    if (x >= xlist[right])
      return right;

    while (left < right - 1) {
      let i = (left + right) / 2 | 0;
      let middle = xlist[i];
      if (x < middle) {
        right = i;
      } else if (x > middle) {
        left = i;
      } else {
        return i;
      }
    }
    return left;
  }

  // 计算给定时间点曲线上的 (x, y) 并分别赋值到对应数组中
  function setBezierPoint (index: number): void {
    if (index === 0) {
      let p = points[0];
      xlist[index] = p[0], ylist[index] = p[1];
      return;
    }

    if (index === segments) {
      let p = points[points.length - 1];
      xlist[index] = p[0], ylist[index] = p[1];
      return;
    }

    let x = 0, y = 0, tmp;
    let t = index / segments, n = l - 1;
    for (let i = 0; i <= n; i++) {
      tmp = combinatorial(n, i) * Math.pow(1 - t, n - i) * Math.pow(t, i);

      let [px, py] = points[i];
      x += tmp * px;
      y += tmp * py;
    }

    xlist[index] = x;
    ylist[index] = y;
  }

  // 对传入fn的参数及执行之后的结果缓存
  function cached (fn) {
    const map = Object.create(null);
    return function cache (...args) {
      let key = args.join(',');
      return map[key] || (map[key] = fn(...args));
    }
  }
}


if (window.requestAnimationFrame) {
  window.startInterval = function (fn, timer) {
    var step = function () {
      if (!fn()) timer.id = window.requestAnimationFrame(step);
    }
    step();
  }

  window.stopInterval = function (timer) {
    window.cancelAnimationFrame(timer && timer.id);
  }
} else {
  window.startInterval = function (fn, timer) {
    var id = setInterval(function () {
      if (!fn()) clearInterval(id);
    }, 1000 / 60);
    timer && (timer.id = id);
  }
  window.stopInterval = function (timer) {
    clearInterval(timer && timer.id);
  }
}


function _animate(stFn: (x: number) => number) {
  let timer = {};
  return function animate (
    range: [number, number],
    t: number,
    fn: (v: number, p: number) => void,
    fnEnd?: Function
  ): Function {
    let [from, to] = range;

    if (from === to)
      return fnEnd && fnEnd();

    let total: number = Math.ceil(t * 60 / 1000); // 总帧数
    let i: number = 0, val: number, percentage: number;

    startInterval(_ => {
      percentage = ++i / total;

      val = from + (to - from) * stFn(percentage);
      fn(val, percentage);
      if (i >= total) {
        fnEnd && fnEnd();
        return true;
      }
    }, timer);

    // 返回一个stop函数以便中途停止动画
    return function stop () {
      stopInterval(timer);
    }
  }
}

const move = {
  linear: _animate(x => x),
  collision: _animate(x => {
    if (x >= 1) return 1;

    let a: number, b: number; // 碰撞点的横坐标
    let times = 10; // 最多查找10条抛物线
    let tmp = 4 / 3;

    for (let i = 1; i < times; i++) {
      a = 1 - tmp * Math.pow(0.5, i - 1);
      b = 1 - tmp * Math.pow(0.5, i);
      if (x >= a && x <= b ) { // 这里可用二分查找法优化
        return Math.pow(3 * (x - (a + b) / 2 ), 2) + 1 - Math.pow(0.25, i - 1);
      }
    }
  }),
  
  ease: _animate(x => {
    return Math.sin(x * Math.PI + Math.PI / 2) / 2 + .5
  }),
  
  bezier: _animate(getBezierCurve([1, 0], [.5, 1])),

  // 扩展更多 位移-时间函数...
  extend: (k, fn) => {
    if (this.hasOwnProperty(k))
      throw new Error(`${k} 已经被声明`);

    this[k] = _animate(fn);
  }
}

let box = document.getElementById('box');

let linearBtn = document.getElementById('linear-btn');
let collisionBtn = document.getElementById('collision-btn');
let bezierBtn = document.getElementById('bezier-btn');

let stop;
linearBtn.onclick = _ => {
  stop && stop();
  let to = document.documentElement.clientWidth - box.offsetWidth;
  stop = move.linear([0, to], 1000, v => {
    box.style.left = v + 'px';
  });
}

collisionBtn.onclick = _ => {
  stop && stop();
  let to = document.documentElement.clientWidth - box.offsetWidth;
  stop = move.collision([0, to], 2000, v => {
    box.style.left = v + 'px';
  });
}

bezierBtn.onclick = _ => {
  stop && stop();
  let to = document.documentElement.clientWidth - box.offsetWidth;
  stop = move.bezier([0, to], 1000, v => {
    box.style.left = v + 'px';
  });
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console