Window.devicePixelRatio

您所在的位置:网站首页 物理a-x图像怎么利用 Window.devicePixelRatio

Window.devicePixelRatio

2023-08-08 17:34| 来源: 网络整理| 查看: 265

在此示例中,我们将设置一个媒体查询并观看它以查看设备分辨率何时更改,以便我们可以检查devicePixelRatio的值来处理所需的任何更新。

JavaScript

JavaScript 代码创建媒体查询,以监控设备分辨率并在每次更改时检查devicePixelRatio的值。

js

let pixelRatioBox = document.querySelector(".pixel-ratio"); let mqString = `(resolution: ${window.devicePixelRatio}dppx)`; const updatePixelRatio = () => { let pr = window.devicePixelRatio; let prString = (pr * 100).toFixed(0); pixelRatioBox.innerText = `${prString}% (${pr.toFixed(2)})`; }; updatePixelRatio(); matchMedia(mqString).addListener(updatePixelRatio);

字符串mqString设置为媒体查询本身。媒体查询以(resolution: 1dppx)(对于标准显示)或(resolution: 2dppx)(对于 Retina / HiDPI 显示)开始,检查当前显示分辨率是否与每个像素px的实际设备像素点匹配。

updatePixelRatio()函数获取devicePixelRatio的当前值,然后将pixelRatioBox的 innerText设置为一个字符串,该字符串同时显示百分比和原始十进制值比率,最多两位小数。

然后,调用updatePixelRatio()函数一次以显示起始值,然后使用matchMedia() 和 addEventListener()来将updatePixelRatio()设置为change事件的处理程序。

HTML

HTML 将创建包含说明的框和将显示当前像素比率信息的pixel-ratio 框。

html

This example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different scaling factor) on the value of the property Window.devicePixelRatio. Try it and watch what happens! CSS

css

body { font: 22px arial, sans-serif; } .container { top: 2em; width: 22em; height: 14em; border: 2px solid #22d; margin: 0 auto; padding: 0; background-color: #a9f; } .inner-container { padding: 1em 2em; text-align: justify; text-justify: auto; } .pixel-ratio { position: relative; margin: auto; height: 1.2em; text-align: right; bottom: 0; right: 1em; font-weight: bold; } 结果



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3