问题
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