在JavaScript中,获取屏幕DPI(Dots Per Inch,每英寸点数)可以通过window.devicePixelRatio
属性结合屏幕的物理尺寸来计算。devicePixelRatio
表示设备像素与CSS像素的比例。
以下是获取屏幕DPI的基本步骤:
function getScreenDPI() {
const devicePixelRatio = window.devicePixelRatio || 1; // 获取设备像素比
const screenWidthInPixels = window.screen.width * devicePixelRatio; // 屏幕宽度(物理像素)
const screenHeightInPixels = window.screen.height * devicePixelRatio; // 屏幕高度(物理像素)
const screenWidthInInches = window.screen.width / devicePixelRatio / 96; // 屏幕宽度(英寸)
const screenHeightInInches = window.screen.height / devicePixelRatio / 96; // 屏幕高度(英寸)
const horizontalDPI = screenWidthInPixels / screenWidthInInches; // 水平DPI
const verticalDPI = screenHeightInPixels / screenHeightInInches; // 垂直DPI
return {
horizontalDPI: horizontalDPI,
verticalDPI: verticalDPI,
averageDPI: (horizontalDPI + verticalDPI) / 2
};
}
const dpiInfo = getScreenDPI();
console.log(`Horizontal DPI: ${dpiInfo.horizontalDPI}`);
console.log(`Vertical DPI: ${dpiInfo.verticalDPI}`);
console.log(`Average DPI: ${dpiInfo.averageDPI}`);
devicePixelRatio
的值可能因设备和浏览器而异,不一定总是准确的。通过上述方法,你可以在JavaScript中获取屏幕的DPI,并根据需要进行相应的处理。
领取专属 10元无门槛券
手把手带您无忧上云