window.devicePixelRatio

If you want to write code that looks nice and crispy in high density displays, you have to take the device pixel density into account. This is exposed to us in JavaScript as the window.devicePixelRatio property, which returns a number that describes how many physical pixels does it take to represent a device independent pixel. The more pixels it takes, the finer the display will look, and the harder it is to actually "see" individual pixels (as in, individual, physical light dots) in the screen. This is famously known now as the "Retina" effect, but not only Mac products exhibit this behaviour-most relatively high end phones with "touch screen" usually have a display density higher than 1.

The interesting bit here is that you can't assume that once a document is opened in your browser, the devicePixelRatio will stay constant. If you drag the window to a screen with a different density, this value will change--as seen in this video where I am dragging my test page window between the Retina display of the laptop, with ratio = 2, and the external monitor whose ratio is 1. For comparison, devicePixelRatio is 3 on my Nexus 5, 1.5 on a Firefox OS Flame, and 1 on a Geeksphone Keon.

Try it out, and maybe leave a comment with what you got!

There isn't any event triggered when this value changes, so that's why in this test case I set a periodic interval to keep updating the value:


setInterval(updateDPR, 50);

function updateDPR() {
    p.textContent = window.devicePixelRatio;
}

Perhaps not the most efficient piece of code, but this is also a bit of a corner case maybe, and a test page, so just don't copy it literally :-)

Sources.