Set viewport to match physical pixels

核能气质少年 提交于 2020-01-02 09:29:10

问题


I'm trying to make the viewport exactly match the physical pixels on the screen.

The page I'm working on's HTML (which I can't change, because that would break other things using the same HTML) includes:

<meta name=viewport content="width=device-width, initial-scale=1">

How would I make the viewport match physical pixels in javascript?


回答1:


What you want to do is layout into a larger viewport and then scale down the page until it fits into the screen.

window.devicePixelRatio is the number of physical pixels per CSS pixel at scale=1.

We'll first adjust the layout width that the page flows into. Since width=device-width is the device viewport width in CSS pixels, you want to multiply that by window.devicePixelRatio so that it's the width of the device viewport in physical pixels. Unfortunately, there's no keyword for this so you have to do it from JS:

// Assuming <html> has `width: 100%`.
var width = document.documentElement.clientWidth * window.devicePixelRatio;
viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=' + width + ', minimum-scale: 1');

However, now your page is wider than the device viewport. You can probably apply the correct viewport-meta scale attributes to shrink it back down but I'd recommend using CSS transforms since they're more interoperable and have fewer quirks than viewport meta, it's likely to work better across browsers. In that case you need to now scale the page down by dividing by the devicePixelRatio:

document.documentElement.style.transform = 'scale( 1 / window.devicePixelRatio )';
document.documentElement.style.transformOrigin = 'top left';

That will shrink your content so that 1 CSS pixel == 1 physical pixel.



来源:https://stackoverflow.com/questions/45610164/set-viewport-to-match-physical-pixels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!