How Can You Get The Css Pixel / Device Pixel Ratio?
Solution 1:
You can use window.devicePixelRatio
in 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.
Solution 2:
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 systemXDPIif (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;
}
elseif (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio;
}
return ratio;
};
Solution 3:
There is a much better CSS/JS solution:
/** sample media query for pixel-ratio=2" **/
@media
(-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi) {
.pixel-ratio-holder:before {
content: "2";
}
}
functionjsPixelRatio(){
returnwindow.getComputedStyle(document.querySelector('.pixel-ratio-holder'), 'before').getPropertyValue('content').replace(/[^a-z]/g,'') * 1;
}
Solution 4:
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:
functiongetDevicePixelRatio() {
var mediaQuery;
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (window.devicePixelRatio !== undefined && !is_firefox) {
returnwindow.devicePixelRatio;
} elseif (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) {
return1.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) {
return2;
}
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) {
return0.7;
}
} else {
return1;
}
}
CanIUse: window.devicePixelRatio
, Window.matchMedia()
Useful links: MDN - window.devicePixelRatio
, MDN - Window.matchMedia()
Post a Comment for "How Can You Get The Css Pixel / Device Pixel Ratio?"