Javascript 如何获得 CSS 像素/设备像素比?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5063489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:28:51  来源:igfitidea点击:

How can you get the CSS pixel / device pixel ratio?

javascriptcsshtml

提问by yonran

I want to find the ratio between CSS pixels and device pixels.

我想找到 CSS 像素和设备像素之间的比率。

Edit: I should have realized that this is just zoom level. I've added an answerto the canonical reference on zoom levels.

编辑:我应该意识到这只是缩放级别。我在缩放级别的规范参考中添加了一个答案

CSS pixels are the unit we use for almost everything--it's what element.style.width, element.clientWidth, element.offsetWidth etc. mean. Device pixels are the pixels that the browser actually paints to. A few properties are measured in device pixels, e.g. window.screen.width, which is the screen size (e.g. 1024) that doesn't change when the user zooms in.

CSS 像素是我们用于几乎所有事物的单位——这就是 element.style.width、element.clientWidth、element.offsetWidth 等的意思。设备像素是浏览器实际绘制的像素。一些属性以设备像素为单位,例如 window.screen.width,这是用户放大时不会改变的屏幕尺寸(例如 1024)。

Motivation: when the user zooms in, I want to increase a canvas's width and height (while keeping style.width and style.height the same CSS pixel value), scale() the context, and redraw on a crisper upscaled canvas.

动机:当用户放大时,我想增加画布的宽度和高度(同时保持 style.width 和 style.height 相同的 CSS 像素值), scale() 上下文,并在更清晰的放大画布上重绘。

I've read Quirksmode's A Tale of Two Viewportsand High DPI on Surfin' Safari, but neither of them say how to get the ratio. The only ideas I have so far are to collect mousemoves and measure change in event.clientX divided by change in event.screenX, or to programatically create media queries using moz--min-device-pixel-ratio, use getComputedStyle()to test whether the rule matched, and narrow it down with a binary search. I hope there's a easier/more reliable way.

我读过Quirksmode 的Surfin' Safari 上的两个视口高 DPI 的故事,但他们都没有说如何获得比例。到目前为止,我唯一的想法是收集 mousemoves 并测量 event.clientX 中的变化除以 event.screenX 中的变化,或者使用编程方式创建媒体查询moz--min-device-pixel-ratio,用于getComputedStyle()测试规则是否匹配,并通过二分搜索缩小范围. 我希望有一种更简单/更可靠的方法。

Edit: I've tried using the @media (-webkit-min-device-pixel-ratio:1)queries with Chrome, Safari, and Firefox 4, and apparently Webkit treats the property as a constant device pixel to screen pixelratio (which doesn't change with zoom), whereas Firefox 4 treats it as device pixel to CSS pixelratio (which increases when you zoom in). So in Firefox 4, I can discover the CSS pixel / device pixel ratio using a binary search, but not with Webkit.

编辑:我尝试在@media (-webkit-min-device-pixel-ratio:1)Chrome、Safari 和 Firefox 4 中使用查询,显然 Webkit 将该属性视为恒定的设备像素与屏幕像素比(不会随缩放而改变),而 Firefox 4 将其视为设备像素与CSS 像素的比率(放大时会增加)。所以在 Firefox 4 中,我可以使用二进制搜索来发现 CSS 像素/设备像素比,但不能使用 Webkit。

回答by Tanzeel Kazi

You can use window.devicePixelRatioin Webkit based browsers to get the device pixel ratio directly in JavaScript. I have used this on Google Chrome, Android browsers (2.2+) and Mobile Safari. I have no idea about other browsers though.

您可以window.devicePixelRatio在基于 Webkit 的浏览器中使用,直接在 JavaScript 中获取设备像素比。我在 Google Chrome、Android 浏览器 (2.2+) 和 Mobile Safari 上使用过它。我不知道其他浏览器虽然。

回答by abhinav sharma

You can always use the following method and it would work in all the browsers

您始终可以使用以下方法,它适用于所有浏览器

window.getDevicePixelRatio = function () {
    var ratio = 1;
    // To account for zoom, change to use deviceXDPI instead of systemXDPI
    if (window.screen.systemXDPI !== undefined && window.screen.logicalXDPI       !== undefined && window.screen.systemXDPI > window.screen.logicalXDPI) {
        // Only allow for values > 1
        ratio = window.screen.systemXDPI / window.screen.logicalXDPI;
    }
    else if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    }
    return ratio;
};

回答by androidavid

There is a much better CSS/JS solution:

有一个更好的 CSS/JS 解决方案:

/** sample media query for pixel-ratio=2" **/
@media  
(-webkit-min-device-pixel-ratio: 2), 
(min-resolution: 192dpi) { 
  .pixel-ratio-holder:before {
   content: "2";
  }
}


function jsPixelRatio(){
   return window.getComputedStyle(document.querySelector('.pixel-ratio-holder'), 'before').getPropertyValue('content').replace(/[^a-z]/g,'') * 1;
}

回答by Andrii Verbytskyi

How to get device Pixel Ratio

如何获取设备像素比

This example uses window.devicePixelRatioas a starting point ANDalso window.matchMedia()Web API as a fallback calculation.

此示例window.devicePixelRatio用作起点window.matchMedia()用作 Web API 作为后备计算。

The browser support for both those features is pretty good, so this should work great for most of use cases.

浏览器对这两个功能的支持都非常好,因此这对于大多数用例来说应该很好用。

Here is a function that retrieves this information, originally written by PatrickJS and published as a GitHub Gist:

这是一个检索此信息的函数,最初由 PatrickJS 编写并作为 GitHub Gist 发布

function getDevicePixelRatio() {
    var mediaQuery;
    var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

    if (window.devicePixelRatio !== undefined && !is_firefox) {
        return window.devicePixelRatio;
    } else if (window.matchMedia) {
        mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
          (min--moz-device-pixel-ratio: 1.5),\
          (-o-min-device-pixel-ratio: 3/2),\
          (min-resolution: 1.5dppx)";
        if (window.matchMedia(mediaQuery).matches) {
            return 1.5;
        }
        mediaQuery = "(-webkit-min-device-pixel-ratio: 2),\
          (min--moz-device-pixel-ratio: 2),\
          (-o-min-device-pixel-ratio: 2/1),\
          (min-resolution: 2dppx)";
        if (window.matchMedia(mediaQuery).matches) {
            return 2;
        }
        mediaQuery = "(-webkit-min-device-pixel-ratio: 0.75),\
          (min--moz-device-pixel-ratio: 0.75),\
          (-o-min-device-pixel-ratio: 3/4),\
          (min-resolution: 0.75dppx)";
        if (window.matchMedia(mediaQuery).matches) {
            return 0.7;
        }
    } else {
        return 1;
    }
}

CanIUse: window.devicePixelRatio, Window.matchMedia()

可以使用: window.devicePixelRatio,Window.matchMedia()

Useful links: MDN - window.devicePixelRatio, MDN - Window.matchMedia()

有用的链接MDN -window.devicePixelRatio, MDN -Window.matchMedia()