设置视口以匹配物理像素 [英] Set viewport to match physical pixels

查看:21
本文介绍了设置视口以匹配物理像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使视口与屏幕上的物理像素完全匹配.

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

我正在处理的页面的 HTML(我无法更改,因为这会破坏使用相同 HTML 的其他内容)包括:

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">

如何使视口与 JavaScript 中的物理像素匹配?

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

推荐答案

您要做的是将页面布局到更大的视口中,然后缩小页面,直到它适合屏幕.

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 是 scale=1 时每个 CSS 像素的物理像素数.

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

我们将首先调整页面流入的布局宽度.由于 width=device-width 是以 CSS 像素为单位的设备视口宽度,因此您希望将其 乘以 window.devicePixelRatio 使其成为宽度设备视口的物理像素.不幸的是,这里没有关键字,所以你必须从 JS 中完成:

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');

但是,现在您的页面比设备视口宽.您可能可以应用正确的 viewport-meta 比例属性来缩小它,但我建议使用 CSS 转换,因为它们比 viewport meta 更具互操作性并且具有更少的怪癖,它可能会在浏览器中更好地工作.在这种情况下,您现在需要通过除以 devicePixelRatio 来缩小页面:

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';

这将缩小您的内容,使 1 个 CSS 像素 == 1 个物理像素.

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

这篇关于设置视口以匹配物理像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆