<h1>Grays with same contrast ratio apart (<span id="count">⏳</span>)</h1>
<ul id="colors">
</ul>
body {
margin: 0;
font-family: "Arial", sans-serif;
}
h1 {
margin: 0;
padding: 16px;
font-weight: normal;
text-align: center;
background: linear-gradient(45deg, #333, #ccc);
}
ul {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(164px, 1fr));
grid-gap: 16px;
padding: 16px 32px;
}
li {
border-radius: 4px;
padding: 48px 16px 16px;
list-style: none;
text-align: end;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.25);
}
const CONTRAST_RATIO = 1.10362; // <- change this for different steps
// five decimals are needed to span from #000000 to exactly #ffffff
const getChannel = (channel) => {
const normalized = channel/255;
if (normalized <= 0.03928) {
return normalized/12.92
} else {
return ((normalized + 0.055) / 1.055) ** 2.4;
}
}
const getLuminance = (r, g, b) => {
const R = getChannel(r);
const G = getChannel(g);
const B = getChannel(b);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
const colors = document.querySelector('#colors');
const addColor = (r, g, b) => {
const li = document.createElement('li');
if (r < 128) { // a bit dirty
li.style.color = 'white';
}
li.innerHTML = `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}<br/>
rgb(${r}, ${g}, ${b})`;
li.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
colors.appendChild(li);
};
let count = 1;
addColor(0, 0, 0);
let previousLuminance = 0;
for (let v = 0; v < 256; v++) {
const luminance = getLuminance(v, v, v);
if (CONTRAST_RATIO < (luminance + 0.05)/(previousLuminance + 0.05)) {
count++;
addColor(v, v, v);
previousLuminance = luminance;
}
}
document.querySelector('#count').textContent = count;
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.