I am trying to create a parallax background effect with some knockout text. I am facing two issues:
The parallax effect does not work at all when background-size: contain; is set.
The parallax effect, for whatever reason, does not work outside of Codepen - when scaled up fully in chrome, the effect disappears and behaves exactly as if the background is stuck to your mouse...I am not sure if this is a scaling issue or issue with chrome and my method.
Here is my code:
(function() {
// Add event listener
document.addEventListener("mousemove", parallax);
const elem = document.querySelector("#text");
// Magic happens here
function parallax(e) {
let _w = window.innerWidth / 2;
let _h = window.innerHeight / 2;
let _mouseX = e.clientX;
let _mouseY = e.clientY;
let _depth1 = `${50 - (_mouseX - _w) * 0.01}% ${50 - (_mouseY - _h) * 0.01}%`;
let _depth2 = `${50 - (_mouseX - _w) * 0.02}% ${50 - (_mouseY - _h) * 0.02}%`;
let _depth3 = `${50 - (_mouseX - _w) * 0.06}% ${50 - (_mouseY - _h) * 0.06}%`;
let x = `${_depth3}, ${_depth2}, ${_depth1}`;
console.log(x);
elem.style.backgroundPosition = x;
}
})();
.background {
background: #000;
}
#text {
background: url("https://images.unsplash.com/photo-1465101162946-4377e57745c3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1957&q=80");
/*background-size: contain;*/
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 8vw;
}
<body class="background">
<h1 id="text"><b>Galaxy</b></h1>
</body>
The solution turned out to be that it depends on the size of the image, which it seems must be smaller than the container (in this case the entire screen/body) in order for this to work.
The image I was using in the above codepen was different to the image I was using in my local instance. To make it behave correctly, I simply applied background-size: 50%; to my much larger local background image so that it behaves more like the smaller background image used in the codepen.