Rémi Rémi - 4 months ago 8
HTML Question

Can I get the size of an html element in screen pixels (not abstract html pixels)?

I wish to use javascript to render a bitmap in a canvas at screen resolution, whatever the zoom level. Is there a way to do it?

I found a similar unanswered question there:
How to get size of an element in physical pixels?

I noticed that html pixels match physical pixels at the default zoom level in Firefox on my desktop. But if I zoom in or out, then they don't match any more. Is there a way to know the zoom level?

Edit: here is my best attempt so far. It does not work with Chrome on Android:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="myp"></p>
<p id="resize"></p>
<canvas id="canvas" width="1" height="1" style="width:50%"></canvas>

<script type="text/javascript">
function reDraw(id)
{
canvas = document.getElementById(id);
rect = canvas.getBoundingClientRect();
size = Math.round((rect.right - rect.left) * window.devicePixelRatio);

canvas.width = size
canvas.height = size

context = canvas.getContext("2d");
imageData = context.createImageData(size, size);

for (i = 0; i < size * size; i++)
{
j = (i / size) + (i % size);
imageData.data[4 * i + 0] = 255*(j & 1);
imageData.data[4 * i + 1] = 255*(j & 1);
imageData.data[4 * i + 2] = 255*(j & 1);
imageData.data[4 * i + 3] = 255;
}

context.putImageData(imageData, 0, 0);
document.getElementById("myp").innerHTML =
"devicePixelRatio = " + window.devicePixelRatio + "; bitmap size = " + size;
}

var x = 0;
function refresh()
{
x += 1;
document.getElementById("resize").innerHTML = "resize counter: " + x;
reDraw("canvas");
}

window.addEventListener('resize', refresh);

refresh()

</script>

</body>
</html>

Answer

window.devicePixelRatio returns a ratio of physical pixels to CSS pixels. On desktop this will usually be the zoom level, on mobile devices it is approximately a ratio of device resolution to 96dpi but it varies highly between the vendors.