Created
May 7, 2018 15:34
-
-
Save prayerslayer/301261c235246d38a88a4e47cee66402 to your computer and use it in GitHub Desktop.
Find used colors on page
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 colorCount() { | |
function trim(str) { | |
return str.replace(/^\s+|\s+$/gm, ''); | |
} | |
function toComponents(str) { | |
return str.match(/rgba?\((.+)\)/)[1].split(',').map(s => s.trim()).map(s => parseInt(s, 10)) | |
} | |
function componentToHex(c) { | |
var hex = c.toString(16); | |
return hex.length == 1 ? '0' + hex : hex; | |
} | |
function rgbToHex(r, g, b) { | |
return ('#' + componentToHex(r) + componentToHex(g) + componentToHex(b)).toUpperCase(); | |
} | |
function rgbaToHex(rgba) { | |
const components = toComponents(rgba); | |
return rgbToHex.apply(null, components) | |
} | |
const colors = Array.from(document.querySelectorAll('*')).reduce( | |
(agg, node) => { | |
const style = window.getComputedStyle(node); | |
const fg = rgbaToHex(style.color); | |
const bg = rgbaToHex(style.backgroundColor); | |
for (const c of [fg, bg]) { | |
if (agg[c] > 0) { | |
agg[c] += 1; | |
} else { | |
agg[c] = 1; | |
} | |
} | |
return agg; | |
}, | |
{} | |
); | |
const colorList = Object.keys(colors).map(color => [color, colors[color]]); | |
colorList.sort((a, b) => (a[1] > b[1] ? -1 : b[1] > a[1] ? 1 : 0)); | |
return colorList.map(val => val[0] + ': ' + val[1]).join('\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment