123

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.

            
              <h1>Animation FPS comparing with Jank!</h1>

<p>
  <button id="timer">animate by setTimeout</button>
  <button id="raf">animate by requestAnimationFrame</button>
  <button id="reset">reset</button>
</p>
<p>
  <label>
    enable continuous jank<input id="toggleJank" type="checkbox" />
  </label>
  <label>
    enable css samples<input id="toggleCssSamples" type="checkbox" />
  </label>
  <label>
    enable <code>will-change</code><input id="toggleWillChange" type="checkbox" />
  </label>
</p>
<p>[SET] <span id="setting">...</span></p>
<p>[FPS] <span id="fps">...</span></p>
<p>[RES] <span id="result">...</span></p>
<hr>
<div class="by-js"></div>
<div class="by-js"></div>
<div class="by-js"></div>
<div class="by-js"></div>
<div class="by-css"></div>
<div class="by-css"></div>
<div class="by-css"></div>
<div class="by-css"></div>

            
          
!
            
              body {
  margin: 0;
  padding: 20px;
}

label {
  border: 1px solid red;
  padding: 3px 5px;
  cursor: pointer;
  margin-right: 10px;
}

.by-js,
.by-css {
  position: relative;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-bottom: 10px;
  background-image: url(https://pbs.twimg.com/profile_images/770463902870241280/ABvREHv0_400x400.png);
  background-size: contain;
/*   background: red; */
}

.by-js {
  border: 3px solid green;
}

.by-css {
  display: none;
  border: 3px solid yellow;
}

.by-js::after,
.by-css::after {
  content: attr(class);
  position: absolute;
  bottom: 0;
  width: 100%;
  display: block;
  text-align: center;
}

.enable-css-samples .by-css {
  display: block;
}

.enable-will-change div {
  will-change: transform;
}
            
          
!
            
              const DELTA       = 800;
const DURATION    = 8000;
const DESIRED_FPS = 60;

const DELTA_PER_FRAME = DELTA / (DURATION / (1000 / DESIRED_FPS));
const TIME_PER_FRAME  = 1000 / DESIRED_FPS;

const toArray   = Function.prototype.call.bind(Array.prototype.slice);
const textures  = toArray(document.getElementsByClassName('by-js'));
const texturesB = toArray(document.getElementsByClassName('by-css'));

const settingContainer = document.getElementById('setting');
const resultContainer  = document.getElementById('result');
const fpsContainer     = document.getElementById('fps');

let rafId, timerId, jankIntervalId;

function add(a, b) { return a + b; }
function sum(...nums) { return nums.reduce(add, 0); }
function ave(...nums) { return sum(...nums) / nums.length; }
function truncate(num) { return Math.floor(num * 100) / 100; }
function rand(min, max) { return Math.random() * (max - min) + min; }

function doAnimate(targets, useRaf = false) {
  const startTime = performance.now();
  const fpsLog    = [];

  let lapLatestTime = startTime;
  let lapDrawCount  = 0;
  let prevFrame     = 0;

  function fps(currentTime) {
    lapDrawCount++;
    if (currentTime - lapLatestTime > 300) {
      fpsLog.push((lapDrawCount / (currentTime - lapLatestTime) * 1000));
      lapLatestTime = currentTime;
      lapDrawCount = 0;
      fpsContainer.innerHTML = `Latest: ${truncate(fpsLog[fpsLog.length - 1])}`;
    }
  }

  function draw() {
    performance.mark('draw-s');
    const currentTime  = performance.now();
    const currentFrame = Math.floor((currentTime - startTime) / TIME_PER_FRAME);
    const currentDelta = Math.min(DELTA, currentFrame * DELTA_PER_FRAME);

    if (prevFrame !== currentFrame) {
      prevFrame = currentFrame;
      targets.forEach((target) => target.style.transform = `translateX(${currentDelta}px)`);
      fps(currentTime);
    }

    if (currentDelta < DELTA) {
      // timer と rAF 分岐
      if (useRaf) {
        rafId = requestAnimationFrame(draw);
      } else {
        timerId = setTimeout(draw, 1000 / DESIRED_FPS);
      }
    } else {
      // complete
      resultContainer.innerHTML = `Elapsed: ${truncate(currentTime - startTime)} ms`;
      fpsContainer.innerHTML += ` / Average: ${truncate(ave(...fpsLog))}`;
    }
    performance.mark('draw-e');
    performance.measure('draw', 'draw-s', 'draw-e');
  }

  draw();
}

function animateTextures(useRaf = false) {
  resetTextures();
  doAnimate(textures, useRaf);
  texturesB.forEach((texture) => {
    texture.style.transition = `transform ${DURATION / 1000}s linear`;
    texture.style.transform = `translateX(${DELTA}px)`;
  });
}

function resetTextures() {
  textures.forEach((texture) => texture.style.transform =null);
  texturesB.forEach((texture) => texture.style.transform = texture.style.transition = null);
  clearTimeout(timerId);
  cancelAnimationFrame(rafId);
}

// event listeners
document.getElementById('raf').addEventListener('click', () => animateTextures(true));
document.getElementById('timer').addEventListener('click', () => animateTextures());
document.getElementById('reset').addEventListener('click', () => resetTextures());

// css transition samples
document.getElementById('toggleCssSamples').addEventListener('click', (e) => {
  if (e.target.checked) {
    document.body.classList.add('enable-css-samples');
  } else {
    document.body.classList.remove('enable-css-samples');
  }
});

document.getElementById('toggleWillChange').addEventListener('click', (e) => {
  if (e.target.checked) {
    document.body.classList.add('enable-will-change');
  } else {
    document.body.classList.remove('enable-will-change');
  }
});

// jank provide
document.getElementById('toggleJank').addEventListener('click', (e) => {
  if (e.target.checked) {
    jankIntervalId = setInterval(jank, 4); // high frequency
  } else {
    clearInterval(jankIntervalId);
  }
});

function jank() {
  performance.mark('jank-s');
  const s = performance.now();
  const e = rand(8, 20); // busy time (ms)
  do {
    if (performance.now() - s > e) {
      break;
    }
  } while (true);
  performance.mark('jank-e');
  performance.measure('jank', 'jank-s', 'jank-e');
}

// show settings
settingContainer.innerHTML = `Delta: ${DELTA} px / Duration: ${DURATION} ms / Desired FPS: ${DESIRED_FPS}`;
            
          
!
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.

Console