Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get divs position after translate3d

In Javascript, when I move an element using the gpu via the translate3d method, the elements style-left position doesnt change at all. As the cpu isnt even aware any motion has occurred.

How do I track what the new position of an element is, after moving it via translate3d?

like image 526
john-jones Avatar asked Feb 03 '15 09:02

john-jones


3 Answers

Use Element.getBoundingClientRect() to get the element coordinates

Here's just a small example that retrieves the .left Rect property from a CSS3 translated (animated) element:

const box = document.getElementById('box');
const printer = document.getElementById('printer');
const printBoxRectLeft = () => {
  printer.textContent = box.getBoundingClientRect().left;
  requestAnimationFrame(printBoxRectLeft);
};

printBoxRectLeft();
#box{
  width:30px; height:30px; background:red;
  animation: animX 3s infinite alternate;
}
@keyframes animX { to{ transform:translateX(300px); }}
<div id="printer"></div>
<div id="box"></div>
like image 103
Roko C. Buljan Avatar answered Nov 11 '22 01:11

Roko C. Buljan


The style attribute left is set to auto if you do not set it manually. But you should be able to use the jquery function position().

    var position = $('#element').position();
    var left = position.left;

http://jsfiddle.net/nqab2aw7/2/

like image 27
oshell Avatar answered Nov 11 '22 01:11

oshell


The other answers that use getBoundingClientRect work in most cases, but it calculates from the viewport, not the DOM's actual 0,0. So if the parent element has negative coords, and is off screen, getBoundingClientRect will return the wrong coordinates.

It also ignores margin, padding, and borderWidth, so if you need to be very precise:

trueLeft = rect.left - margin.left - padding.left - borderWidth - offsetX

to get the other values could use a RegExp:

'translate3d(256px, 512px, 0px)'.replace(/translate3d|px|\(|\)/gi, '').split(',');

// { x: trueLeft, y: translate3d[1], z: translate3d[2] }
like image 1
Benny Nightingale Avatar answered Nov 11 '22 03:11

Benny Nightingale