I want to find the ratio between CSS pixels and device pixels.
Edit: I should have realized that this is just zoom level. I've added an answer to the canonical reference on zoom levels.
CSS pixels are the unit we use for almost everything--it's what element.style.width, element.clientWidth, element.offsetWidth etc. mean. Device pixels are the pixels that the browser actually paints to. A few properties are measured in device pixels, e.g. window.screen.width, which is the screen size (e.g. 1024) that doesn't change when the user zooms in.
Motivation: when the user zooms in, I want to increase a canvas's width and height (while keeping style.width and style.height the same CSS pixel value), scale() the context, and redraw on a crisper upscaled canvas.
I've read Quirksmode's A Tale of Two Viewports and High DPI on Surfin' Safari, but neither of them say how to get the ratio. The only ideas I have so far are to collect mousemoves and measure change in event.clientX divided by change in event.screenX, or to programatically create media queries using moz--min-device-pixel-ratio
, use getComputedStyle()
to test whether the rule matched, and narrow it down with a binary search. I hope there's a easier/more reliable way.
Edit: I've tried using the @media (-webkit-min-device-pixel-ratio:1)
queries with Chrome, Safari, and Firefox 4, and apparently Webkit treats the property as a constant device pixel to screen pixel ratio (which doesn't change with zoom), whereas Firefox 4 treats it as device pixel to CSS pixel ratio (which increases when you zoom in). So in Firefox 4, I can discover the CSS pixel / device pixel ratio using a binary search, but not with Webkit.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…