'Javascript request animation frame irregular translation
SO community! I'm trying to make an object move at the same phase as scroll using CSS transform. The problem is that I see the animation is not smooth. Instead, is like the box is flickering and 'jumping' all the time, and I can't figure out the cause.
How can I achieve these kinds of transformations in a smooth way?
I will leave my code below, as well as a codepen link.
Thanks beforehand for your help!
const container = document.querySelector('.container');
const box = document.querySelector('.box');
function animate() {
transformBox();
requestAnimationFrame(animate);
}
function transformBox() {
const scrollY = window.scrollY;
box.style.transform = `translate3d(0, ${scrollY}px, 0)`;
}
animate();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
overscroll-behavior: none;
}
.container {
position: relative;
height: 400vh;
background-color: #333;
}
.box {
position: absolute;
top: calc(50vh - 25px);
left: calc(50% - 25px);
width: 50px;
height: 50px;
background-color: white;
border-radius: 8px;
}
<div class="container">
<div class="box"></div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
