Solution 1 :

Say hello to window.devicePixelRatio:

var el = document.querySelector('img');

function getElemSize(el) {
  var rect = el.getBoundingClientRect();
  return {
    width: Math.round(rect.width * window.devicePixelRatio),
    height: Math.round(rect.height * window.devicePixelRatio)

function updateSize() {
  var size = getElemSize(el);
  document.querySelector('p').innerHTML = JSON.stringify(size);

el.addEventListener('load', updateSize);
addEventListener('resize', updateSize);
<img src="" style="width: 150px">

Solution 2 :

You can use the visualViewport API to multiply the width by the scale if you’re looking for pinch zoom:

const { scale } = window.visualViewport;
const width = $(elem).width() * scale;

I tried adding a snippet for an example, but according to the spec the window.visualViewport.scale inside of an iframe is always 1. As long as your content is not in an iframe, this method will work for giving you the scale of the pinch zoom (tested in my browser console)

Problem :

To illustrate my question, here is a not-real example:

<img src='myimage-low.png' style='width: 150px;'>
<img src='myimage-high.png' style='width: 150px;'>

myimage-low.png is 150px x 100px

myimage-high.png is 1500px x 1000px

When I am zoomed all the way out on the web page, both images look the same. When I zoom in, the high definition image looks much better.

If I use javascript to get the image width with $(elem).width();, it says (as I would expect) 150px for both, regardless of the zoom.

Is there a way in javascript to get the actual screen size of the element as presented to the user? In my above example, they might both say “100px” when I’m fully zoomed out, and “1000px” when I’m fully zoomed in.

Note – I need to be able to need this for both <img> elements as well as any element that might have a css background-image.

For context, this is to determine which resolution of an image to load. There’s no point in loading the 1500px if the user is on a low resolution and it will just be resized in the browser to 300px – they might as well have the 500px version which is faster to download.


Comment posted by user2864740

Also really depends on DPI etc.. what is “clear at one inch”?

Comment posted by awarrier99

Are you asking for pinch zoom? Or browser zoom?

Comment posted by awarrier99

When running this in Chrome I get height of

Comment posted by blex

Sorry, I fixed the first run (wasn’t waiting for the image to be loaded). Oh, didn’t think of pinch to zoom, sorry. I only know this technique for browser zoom

Comment posted by blex

@awarrier99 Wait, don’t accept if this doesn’t work for your use (pinch to zoom). Maybe there is a better solution for that scenario

Comment posted by awarrier99

Oh I wasn’t the original poster, I’m not sure whether they were intending for pinch zoom or not, and yeah first run looks good now

Comment posted by blex

@awarrier99 Ah, I thought you were 🙂