Reputation: 1805
I am working on a JavaScript animation library and ran into a problem: All values are usually returned in pixels using this default function:
window.getComputedStyle(element).getPropertyValue(property);
However, when getting the value for background-position like so:
window.getComputedStyle(element).getPropertyValue('background-position');
The result is 50% 50% (background-position: center). How can I convert the values to pixels? I wrote the following function, but it gives me the wrong result, the reason being is that percentages on background-position are also relative to the image size.
var pixelsX = (parseFloat(percentX) / 100 * element.offsetWidth) + 'px';
var pixelsY = (parseFloat(percentY) / 100 * element.offsetHeight) + 'px';
I also cannot get the size using Image() since the calculation has to happen in real time and I cannot wait for the image to load.
Thanks!
Upvotes: 4
Views: 1885
Reputation: 83
If you just need the position of the element, maybe try this:
element.getBoundingClientRect(); (source: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect)
You can get the position of each corner as well as dimensions of the element like so: element.getBoundingClientRect().left;
This returns properties: left, top, right, bottom, x, y, width, and height. All in pixels!
Upvotes: 0
Reputation: 4148
I actually did tried your code and it works... Is this not the accurate sizes? I checked it on different screen sizes and it seems accurate.
Please have a look:
var demoDiv = document.getElementById('divDemo');
var demoCalc = window.getComputedStyle(demoDiv).getPropertyValue('background-position');
var pixelsX = (parseFloat(demoCalc) / 100 * demoDiv.offsetWidth) + 'px';
var pixelsY = (parseFloat(demoCalc) / 100 * demoDiv.offsetHeight) + 'px';
console.log(demoCalc);
console.log(pixelsX);
console.log(pixelsY);
body {height: 100vh; width: 100vw; overflow: hidden}
#divDemo {
height: 100%; width: 100%;
background-image: url(https://images.unsplash.com/photo-1554056588-6c35fac03654?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80);
background-position: 50% 50%;
background-repeat: no-repeat;
}
<div id="divDemo"></div>
More SO on this subject here
Upvotes: 0