How to get the size of an element in physical pixels?

Let's say I have a div that I defined as (32px, 32px) in size:

HTML

 <div id="theBox"></div> 

CSS

 div { width: 32px; height: 32px; background-color: gray; } 

( Live jsFiddle view )

How can I get the actual window size in pixels?

You will notice that the field should not be 32px . It may be more:

enter image description here

or less:

enter image description here

or exactly 32 pixels :

enter image description here

The reason for the differences, of course, is that Chrome and Internet Explorer let me zoom in.

I would like to know the size of the actual item. What for? There is no reason; just because. I am curious, and I would like to expand the limits of human knowledge and understanding.

Or because I need to set the internal resolution of the Canvas element so that it matches the actual size of the canvas element - otherwise the displayed contents of the canvas will be stretched without my permission:

enter image description here

Although my reasons for not knowing the size of the item are not necessarily applicable only to the canvas. I ask about a common div element; and the answer will be used for Canvas , img , video and everything that I want.

+4
source share
1 answer

You will need to determine the zoom level.

Then write a simple arithmetic proportion to calculate the β€œactual” size or size as it appears to the user.

 var zoomLevel, , actualSize = 32 , viewSize; function getZoomLevel(){ ... your code here...return zoomLevel;} function getViewSize(actualSize){ viewSize = actualSize*getZoomLevel(); return viewSize; } 

Then ... calling getViewSize() when ready ...

Hope the math will be clear. Solution for y (or viewSize):

 actualSize/1 = y/zoomLevel 

However, you need to be careful about subpixel accuracy, especially among well-known browsers with a large length and width error, such as IE9. But, for now, all you need is something close, it should work.

+1
source

Source: https://habr.com/ru/post/1487795/


All Articles