Changing the text color to white when the background color is black works great using mix-blend-mode: difference
. Move the mouse to the text to see the effect:
const blackBox = document.querySelector(".black-box");
window.addEventListener('mousemove', function(event) {
blackBox.style.left = `${event.pageX - 50}px`;
blackBox.style.top = `${event.pageY - 50}px`;
});
.wrapper {
background-color: white;
}
h1 {
position: relative;
z-index: 2;
color: white;
mix-blend-mode: difference;
}
.black-box {
width: 100px;
height: 100px;
position: absolute;
z-index: 1;
background-color: black;
}
<div class="wrapper">
<h1>Lorem Ipsum</h1>
</div>
<div class="black-box"></div>
This understandably doesn't result in white text if the background is anything other than black:
const box = document.querySelector(".box");
window.addEventListener('mousemove', function(event) {
box.style.left = `${event.pageX - 50}px`;
box.style.top = `${event.pageY - 50}px`;
});
.wrapper {
background-color: white;
}
h1 {
position: relative;
z-index: 2;
color: white;
mix-blend-mode: difference;
}
.box {
width: 100px;
height: 100px;
position: absolute;
z-index: 1;
background-image: url("https://placekitten.com/100/100")
}
<div class="wrapper">
<h1>Lorem Ipsum</h1>
</div>
<div class="box"></div>
Is there any way to make it so the text changes color from black to white as soon as the background differs from white?