Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
480 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...