Created
March 1, 2024 00:47
-
-
Save coleww/d3039ec185c8c20240a5d164d446d686 to your computer and use it in GitHub Desktop.
Compute responsive sizes
This file contains hidden or 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
// 1. Paste the first script into the console | |
// 2. Slowly resize the browser window, covering full range | |
// 3. Paste the second script into the console | |
// This could probably be a browser extension that overlays the data on each image... | |
// SCRIPT ONE | |
// breakpoint values that we want to calculate `sizes` for | |
const breakpoints = [768, 1280, 1536, Infinity]; | |
const imageMap = {} | |
// Whenever the window resizes, track in the image map what the size of the image and screen width were | |
const ro = new ResizeObserver( entries => { | |
const sw = window.innerWidth | |
for (let entry of entries) { | |
const cr = entry.contentRect; | |
// key for the images. could be id, data- attr, etc. | |
const img = entry.target.src; | |
if (!imageMap[img]) { | |
imageMap[img] = [] | |
} | |
imageMap[img].push([cr.width, sw]); | |
} | |
}); | |
document.querySelectorAll('img').forEach((el) => ro.observe(el)) | |
// SCRIPT TWO | |
const data = Object.entries(imageMap).map(([image, sizes]) => { | |
// For each image, group the data we collected by breakpoints | |
const sizesByBp = Object.groupBy(sizes, ([_, screenWidth]) => { | |
return breakpoints.find((bp) => screenWidth < bp) | |
}) | |
// For each breakpoint, find the largest possible VW that the image renders at for that breakpoint | |
const vwByBp = Object.entries(sizesByBp).map(([bp, sizes]) => { | |
const vw = Math.max(...sizes.map(([imgWidth, screenWidth]) => Math.ceil((imgWidth / screenWidth) * 100))) | |
return [bp, `${vw}vw`] | |
}) | |
return [image, vwByBp] | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment