Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

javascript - How can you get the CSS pixel / device pixel ratio?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...