My attempt to smoothly move a box from one position to another using Linear Interpolation is not working as expected. The box just moves without any easing effect. I came across a post on Stack Overflow titled C# Lerping from position to position, but I may be misinterpreting the equation provided. Here is my current code:
const lerp = (start, end, speed) => start + (end - start) * speed
const div = document.querySelector('div')
const btn = document.querySelector('button')
let pos = 0
let startTime = 0
const duration = 2000
let aF = null
const animate = () => {
const elapsed = Date.now() - startTime
const t = elapsed / duration
if(elapsed < duration) {
pos = lerp(0, 300, t)
aF = requestAnimationFrame(animate)
} else {
cancelAnimationFrame(aF)
aF = null
pos = 300
}
console.log(pos, 300 * t)
div.style.transform = `translateX(${pos}px)`
}
btn.addEventListener('click', () => {
pos = 0
startTime = Date.now()
aF = requestAnimationFrame(animate)
})
div {
width: 50px;
height: 50px;
background: green;
}
button {
margin-bottom: 10px;
}
<button>Run Animation</button>
<div></div>
In the code example above, the box animates without any easing effect. The values in the console logs remain the same even though the intention was to apply linear interpolation on one value and not the other.
I'm aware that there might be something I'm missing or misunderstanding here. Any assistance or insight would be greatly appreciated. Thank you.