Created
August 22, 2023 08:15
-
-
Save mjot/9f8d3142acbbc217b56419f17a09fc98 to your computer and use it in GitHub Desktop.
This JavaScript snippet provides utility to determine and log the aspect ratio of the current browser viewport. Key functionalities include: Greatest Common Divisor (GCD) Calculation: A helper function to determine the GCD of two numbers, which aids in simplifying the aspect ratio.
Aspect Ratio Determination: Computes the simple aspect ratio (e.…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
/** | |
* Calculate the greatest common divisor (GCD) of two numbers. | |
* @param {number} a - First number | |
* @param {number} b - Second number | |
* @returns {number} - The GCD of the two numbers | |
*/ | |
function gcd(a, b) { | |
return (b === 0) ? a : gcd(b, a % b); | |
} | |
/** | |
* Determine the aspect ratio for a given width and height. | |
* @param {number} width - The width | |
* @param {number} height - The height | |
* @returns {Object} - The simple aspect ratio and the CSS min-aspect-ratio value | |
*/ | |
function getAspectRatio(width, height) { | |
var divisor = gcd(width, height); | |
return { | |
simpleRatio: (width / divisor) + ':' + (height / divisor), | |
cssRatioValue: parseFloat((width / height).toFixed(2)) | |
}; | |
} | |
/** | |
* Log the current viewport dimensions and aspect ratios. | |
*/ | |
function logAspectRatio() { | |
var width = window.innerWidth; | |
var height = window.innerHeight; | |
var aspectRatio = getAspectRatio(width, height); | |
console.log(`Viewport size: ${width}x${height}, Aspect Ratio: ${aspectRatio.simpleRatio}, CSS min-aspect-ratio value: ${aspectRatio.cssRatioValue}`); | |
} | |
// Add an event listener to log the aspect ratio when the viewport is resized | |
window.addEventListener('resize', logAspectRatio); | |
// Log the current aspect ratio on page load | |
logAspectRatio(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment