如何获取物理像素中的元素的大小? [英] How to get size of an element in physical pixels?
问题描述
假设我有一个 div
,我已经定义为(32px,32px)
html :
div id =theBox>< / div>
css :
div {
width:32px;
height:32px;
background-color:gray;
}
如何获取框的实际大小(以像素为单位)?
你会注意到,这个框不必是 32px
。可以更大:
或更小:
或正确 32像素
:
不同的原因当然是因为Chrome和Internet Explorer允许我缩放。
我想知道元素的 实际 大小。为什么?没有理由;正当的原因。我很好奇,我想拓宽人类知识和理解的极限。
或者因为我需要设置<$ c $的内部分辨率c> Canvas 元素以匹配画布元素的实际大小,否则在未获得我许可的情况下,已渲染的画布内容将会被拉伸:
>
虽然,我想知道一个元素的大小的原因不一定只适用于一个画布。我问一个通用的div元素;并且答案将用于 canvas
, img
,视频
您需要检测缩放级别。
然后写一个简单的算术比例来计算实际大小或用户看起来的大小。
var zoomLevel,
,actualSize = 32
,viewSize;
function getZoomLevel(){...你的代码在这里... return zoomLevel;}
function getViewSize(actualSize){
viewSize = actualSize * getZoomLevel();
return viewSize;
}
然后...调用 getViewSize code>准备好了...
希望数学是清楚的enuff。
解决y(或viewSize):
actualSize / 1 = y / zoomLevel
$然而,你需要小心亚像素的精度,特别是在像IE9这样的出错的长度/宽度决定的浏览器中。但是,只要你需要的是接近的东西,这应该工作。
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;
}
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:
or smaller:
or exactly 32 pixels
:
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:
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.
解决方案 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.
这篇关于如何获取物理像素中的元素的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!