Detect retina displays with javascript

来源:互联网 发布:减肥过快皮肤松弛 知乎 编辑:程序博客网 时间:2024/06/11 21:59

用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:

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 ifstatement 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">';}
原创粉丝点击