我希望使用javascript在屏幕分辨率下在画布中渲染位图,无论缩放级别如何。有办法吗?
我在那里找到了一个类似的悬而未决的问题: How to get size of an element in physical pixels?
我注意到html像素与桌面上Firefox中默认缩放级别的物理像素匹配。但如果我放大或缩小,那么它们就不再匹配了。有没有办法知道缩放级别?
编辑:到目前为止,这是我最好的尝试。它不适用于Android上的Chrome:
<!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>
答案 0 :(得分:1)
window.devicePixelRatio
返回物理像素与CSS像素的比率。在桌面上,这通常是缩放级别,在移动设备上,它大约是设备分辨率与96dpi的比率,但在供应商之间差别很大。