Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size of an element in physical pixels?

Tags:

html

canvas

Let's say i have a div that i've defined to be (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 size of the box in pixels?

You'll note that the box doesn't have to be 32px. It can be larger:

enter image description here

or smaller:

enter image description here

or exactly 32 pixels:

enter image description here

The reason for the differences, of course, is because Chrome and Internet Explorer allow me to zoom.

i would like to know the actual size of the element. Why? No reason; just cause. i'm curious, and i'd like to broaden the limits of human knowledge and understanding.

Or because i need to set the internal resolution of a Canvas element to match the actual size of the canvas element - otherwise the rendered canvas contents will get stretched without my permission:

enter image description here

Although, my reasons for wanting to know the size of an element do not necessarily apply just to a Canvas. i'm asking about a generic div element; and the answer will be used towards canvas, img, video, and anything else i desire.

like image 255
Ian Boyd Avatar asked Nov 12 '22 02:11

Ian Boyd


1 Answers

You would need to detect the zoom level.

Then write a simple arithmetic proportion to calculate the 'actual' size, or the 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 ... call getViewSize() when ready ...

Hopefully the math is clear enuff. Solving for y (or viewSize):

actualSize/1 = y/zoomLevel

However, you will need to be careful about sub-pixel precision, especially among the notoriously bad length/width determining browsers like IE9. But, as long as all you need is something close, this should work.

like image 199
cliffbarnes Avatar answered Nov 15 '22 05:11

cliffbarnes