JSFiddle - React, Tailwind, and code Playground
by zhylmzr
HTML
<div class="app">
<div class="text">CLICK ME</div>
</div>
CSS
* {
margin: 0;
padding: 0;
}
.app {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: var(--back-color);
}
.text {
color: var(--fore-color);
}
JavaScript
let app, text;
let bg = {
b: 0.17174093274599694,
g: 0.15121412803532008,
r: 0.45364238410596025,
};
function calcTextColor(bg) {
let r = 96 / 255;
if (Math.max(bg.r, bg.g, bg.b) > 1 - r) {
r *= -1;
}
return rgb({
r: limit(bg.r + r),
g: limit(bg.g + r),
b: limit(bg.b + r),
});
}
function calcBgColor(bg) {
return rgb({
b: limit(bg.b),
g: limit(bg.g),
r: limit(bg.r),
});
}
function rgb(o) {
return `rgb(${o.r}, ${o.g}, ${o.b})`;
}
function limit(v) {
return Math.max(0, Math.min(255, Math.round(v * 255)));
}
function changeColor() {
app.setAttribute("style", `--back-color: ${calcBgColor(bg)}`);
text.setAttribute("style", `--fore-color: ${calcTextColor(bg)}`);
}
window.onload = () => {
app = document.getElementsByClassName("app")[0];
text = document.getElementsByClassName("text")[0];
changeColor();
app.addEventListener("click", () => {
bg.b = Math.random();
bg.g = Math.random();
bg.r = Math.random();
changeColor();
});
};