Detect retina displays with javascript
4732 ワード
javascriptで網膜スクリーンかどうかを検出する
I've been trying a way to detect a device's DPI for mobile design. While I haven't yet, I did at least find a way to detect whether the user is using a retina display. So without ado, here's how:
Now the variable
A good is exam ple is if I have a 100x100 image (or video), the above code will tell me to upscale the image to 200x200 for it to look crisp on an iPhone 4 without forcing all users to unnecessarily download a 200x200 image. Especially given bandwidth is a major concern for mobile users.
I've been trying a way to detect a device's DPI for mobile design. While I haven't yet, I did at least find a way to detect whether the user is using a retina display. So without ado, here's how:
var retina = window.devicePixelRatio > 1 ? true : false;
Now the variable
retina
will be set to true
if the user has a retina display. A simple if
statement can be used anywhere to execute code based on the user's display. if (retina) {
// the user has a retina display
}
else {
// the user has a non-retina display
}
Why?
A good is exam ple is if I have a 100x100 image (or video), the above code will tell me to upscale the image to 200x200 for it to look crisp on an iPhone 4 without forcing all users to unnecessarily download a 200x200 image. Especially given bandwidth is a major concern for mobile users.
if (retina) {
var html = '<img src="my-high-res-image.jpg">';
}
else {
var html = '<img src="my-low-res-image.jpg">';
}