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

前端 未结 4 1853
臣服心动
臣服心动 2020-12-04 16:36

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

Edit: I should have realized that this is just zoom level. I\'ve added an answer to t

4条回答
  •  青春惊慌失措
    2020-12-04 16:59

    How to get device Pixel Ratio

    This example uses window.devicePixelRatio as a starting point AND also window.matchMedia() Web API as a fallback calculation.

    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:

    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()

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

提交回复
热议问题