What are best practices for detecting pixel ratio/density?

后端 未结 2 1826
刺人心
刺人心 2020-12-05 09:52

I am currently using JavaScript for mobile device detection on my website, this then allows me to serve different content for mobile or desktop users.

Currently I us

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 10:47

    There is a Generic Solution to get device Pixel Ratio

    Next code uses window.devicePixelRatio as a starting point BUT also has a fallback based on window.matchMedia() Web API.

    The browser support for both those features is almost perfect, 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;
        }
    }
    

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

    CanIUse: window.devicePixelRatio, Window.matchMedia()

提交回复
热议问题