Display Detection API & Snippet Library (JS / CSS)
As frontend engineers and web developers, detecting screen metrics is critical to optimizing user experience, handling display asset scaling, and configuring interactive games. This page is a copy-paste developer cheat sheet. Vetted against W3C standards and optimized for performance.
1. Screen & Viewport Dimensions (JavaScript)
This snippet detects the physical screen specifications, logical viewport coordinates, and active browser scrollbar space in standard pixels:
// 1. Detect physical hardware screen resolution
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
// 2. Detect logical browser viewport dimensions (CSS Pixels)
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
// 3. Detect maximum usable display dimensions (excluding OS taskbar)
const usableWidth = window.screen.availWidth;
const usableHeight = window.screen.availHeight;
console.log({
physicalScreen: `${screenWidth}x${screenHeight}`,
viewportCanvas: `${viewportWidth}x${viewportHeight}`,
usableWorkspace: `${usableWidth}x${usableHeight}`
});
2. Device Pixel Ratio (DPR) Detection
Detect high-density (Retina / HiDPI) displays to dynamically swap asset packs or render sharp vector graphics:
// Get device pixel ratio scaling factor (defaults to 1.0)
const dpr = window.devicePixelRatio || 1;
// Evaluate display density tier
let densityTier = "Standard (1x)";
if (dpr >= 3) {
densityTier = "Ultra-High Density (3x / Retina HD)";
} else if (dpr >= 2) {
densityTier = "High Density (2x / Retina)";
} else if (dpr > 1) {
densityTier = "Medium Density (HiDPI)";
}
console.log(`Scale factor: ${dpr} (${densityTier})`);
3. Responsive Canvas scaling (Retina Canvas Fix)
Without pixel-ratio aware scaling, drawing graphics on an HTML5 <canvas> results in blurry lines and anti-aliasing artifacts on high-DPI monitors. Scale the canvas coordinate grid using the DPR to fix this:
function createSharpCanvas(canvasId, logicalWidth, logicalHeight) {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
// Get current device scaling factor
const dpr = window.devicePixelRatio || 1;
// Set physical drawing buffer size
canvas.width = logicalWidth * dpr;
canvas.height = logicalHeight * dpr;
// Set logical layout display size
canvas.style.width = logicalWidth + 'px';
canvas.style.height = logicalHeight + 'px';
// Scale canvas coordinate grid to physical buffer ratio
ctx.scale(dpr, dpr);
return ctx;
}
// Example usage: Creates a pixel-perfect 400x300 canvas
// const ctx = createSharpCanvas('my-canvas', 400, 300);
4. High-DPI / Retina Media Queries (CSS)
Use modern CSS media queries to apply custom high-density styling or serve high-resolution asset backdrops:
/* Standard resolution displays */
.hero-banner {
background-image: url('hero-1x.jpg');
}
/* High-DPI / Retina displays (DPR >= 2.0) */
@media
(-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi),
(min-resolution: 2dppx) {
.hero-banner {
background-image: url('hero-2x.jpg');
}
}
/* Ultra-high resolution displays (DPR >= 3.0) */
@media
(-webkit-min-device-pixel-ratio: 3),
(min-resolution: 288dpi),
(min-resolution: 3dppx) {
.hero-banner {
background-image: url('hero-3x.jpg');
}
}
5. Refresh Rate Detection (JavaScript)
Because there is no direct Web API to read a displayβs refresh rate (Hz), developers must measure it. This lightweight function benchmarks frames per second (FPS) via browser animation callbacks to detect standard refresh rates (e.g. 60Hz, 120Hz, 144Hz):
function detectDisplayHz(callback) {
let frameCount = 0;
let startTime = performance.now();
function checkFrame() {
frameCount++;
const elapsed = performance.now() - startTime;
if (elapsed >= 1000) {
const estimatedHz = Math.round((frameCount * 1000) / elapsed);
callback(estimatedHz);
} else {
requestAnimationFrame(checkFrame);
}
}
requestAnimationFrame(checkFrame);
}
// Example usage:
// detectDisplayHz(hz => console.log(`Detected refresh rate: ${hz}Hz`));
Methodology Note & Technical Accuracy Disclosure
At screenres.app, all developer snippets are meticulously verified against standard W3C Web specs. Canvas scale techniques conform strictly to the HTML Living Standard. The display refresh rate estimation matches standardized Chrome and Safari frame paint architectures. The CSS DPI/DPPX media queries conform strictly to Media Queries Level 5. All copy-paste widgets are free to utilize in commercial and personal frameworks without royalties.