Skip to content

Instantly share code, notes, and snippets.

@coleww
Created March 1, 2024 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coleww/d3039ec185c8c20240a5d164d446d686 to your computer and use it in GitHub Desktop.
Save coleww/d3039ec185c8c20240a5d164d446d686 to your computer and use it in GitHub Desktop.
Compute responsive sizes
// 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