Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Get Current Position of Animated Element

So I have an element that is using CSS3 transitions to move across the page. I'm trying to see how the actual output FPS of that animation on the page is (for instance, if the page is outputting at 5FPS, a div moving from 0px to 10px at a transition value of 1s should report back 2px, 4px, 6px, etc).

Instead, I just get whatever value I already set the div's position to.

// css has defined a transition of 10s on the moving div
document.getElementById("movingDiv").style.left = "0px";
console.log(document.getElementById("movingDiv").style.left); //outputs 0px
document.getElementById("movingDiv").style.left = "100px";
window.setTimeout(function(){
    console.log(document.getElementById("movingDiv").style.left); //outputs 100px instead of, for instance, 43px or wherever the div would visually appear to be
}, 3000);

That's not the exact code, but just some that's generic enough to illustrate my point.

Restating the question, how would I find where an element visually appears to be during its transition between one position and another? I'm not using jQuery animations as many others have answered for, and don't just want to calculate where the element should be. I want to see where the element actually appears to be on the page. I would also like if this works off-screen as well (like to the left of or above the visible window).

To help see why I'm actually trying to do this, is that I'm trying to get the FPS output of the page. I have seen many cases where the page outputs terrible FPS but Javascript still outputs over 100 FPS because the Javascript can run faster than the page can render itself which I'm trying to avoid.

like image 624
MineAndCraft12 Avatar asked Oct 24 '25 04:10

MineAndCraft12


1 Answers

You can use window.requestAnimationFrame:

  var moving = false,
      el = document.getElementById("mover");
  el.className = el.className + " move-right";
  el.addEventListener('transitionend', function () {
    moving = true;
  });

  function getPosition() {
    var rect = el.getBoundingClientRect()
    console.log(rect.top, rect.left);
    if (!moving) {
      window.requestAnimationFrame(getPosition);
    }
  }
  window.requestAnimationFrame(getPosition);

http://jsfiddle.net/ob7kgmbk/1/

like image 123
dcochran Avatar answered Oct 25 '25 16:10

dcochran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!