Skip to content

Instantly share code, notes, and snippets.

@MattyQ
Created May 29, 2024 14:35
Show Gist options
  • Save MattyQ/e8295250e4a281f8b852132a3367cc9f to your computer and use it in GitHub Desktop.
Save MattyQ/e8295250e4a281f8b852132a3367cc9f to your computer and use it in GitHub Desktop.
Simple function to determine whether a viewport is vertical, horizontal or square, and whether the dimensions are nearest to 16:9, 4:3, or 1:1 (or the vertical equivalent)
function analyzeViewport() {
const width = window.innerWidth;
const height = window.innerHeight;
// Determine layout
let layout;
if (width > height) {
layout = "horizontal";
} else if (width < height) {
layout = "vertical";
} else {
layout = "square";
}
// Determine aspect ratio closeness
const aspectRatio = width / height;
const ratios = {
"16:9": 16 / 9,
"9:16": 9 / 16,
"4:3": 4 / 3,
"3:4": 3 / 4,
"1:1": 1
};
let closestRatio = "";
let smallestDifference = Infinity;
for (const [ratio, value] of Object.entries(ratios)) {
const difference = Math.abs(aspectRatio - value);
if (difference < smallestDifference) {
smallestDifference = difference;
closestRatio = ratio;
}
}
return {
width: width,
height: height,
layout: layout,
closestRatio: closestRatio
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment