Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save patrickkettner/ad496a6acbaa3b28dbe1fb88aeb25a9e to your computer and use it in GitHub Desktop.
Save patrickkettner/ad496a6acbaa3b28dbe1fb88aeb25a9e to your computer and use it in GitHub Desktop.
function getURLOfLargestBackgroundImage() {
var _elms = new Map();
var _canidates = new Map();
const HEIGHT = document.documentElement.clientHeight * 1.4;
const WIDTH = document.documentElement.clientWidth;
const GRANULARITY_IN_PX = 10
const MIN_WIDTH = 150
const MIN_HEIGHT = 150
for (let i = 0; i < HEIGHT; i += GRANULARITY_IN_PX) {
for (let j = 0; j < WIDTH; j += GRANULARITY_IN_PX) {
let elm = document.elementFromPoint(i, j);
let count = _elms.get(elm) || 0
_elms.set(elm, ++count)
}
}
for (var [elm, count] of _elms) {
// elementFromPoint can return null or "none", so just dump if thats the case
if (!(elm instanceof Element)) {
_elms.delete(elm);
continue;
}
const style = getComputedStyle(elm);
const width = parseInt(style.width) || 0;
const height = parseInt(style.height) || 0;
let bg = style.backgroundImage
// delete elements that are too small, or don't have an actual background image
if (width < MIN_WIDTH || height < MIN_HEIGHT || !bg.includes('url')) {
_elms.delete(elm);
continue
}
// get the actual url of the image
bg = bg.match(/(?:.*url\(['"]?([^'"]+)['"]?)/)[1]
_canidates.set(bg, count);
}
// looks gross, but just a oneliner to get get the key value (which is an element ref) with the largest count value
var largestElm = [..._canidates.entries()].reduce((a, b) => a[1] > b[1] ? a : b, [])[0]
return largestElm
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment