Javascript
가속 animation javascript
F.E.D
2021. 2. 2. 23:49
animation 가속과 감속을 자유롭게 이루어내는 javascript 가속도에 대한 코드.
<div class="smoothBox"></div>
.smoothBox { position:fixed; left:0; top:300px; width:0; height:200px; background:hotpink; }
const box = document.querySelector('.box');
const smoothBox = document.querySelector('.smoothBox');
const accelearation = 0.1;
let delay = 0;
let requestAnimationId;
let animState;
let approx;
const anim = () => {
delay = delay + (pageYOffset - delay) * accelearation;
smoothBox.style.width = `${delay}px`;
requestAnimationId = requestAnimationFrame(anim);
approx = Math.abs(pageYOffset - delay) < 1;
if(!approx) return;
cancelAnimationFrame(requestAnimationId);
animState = false;
};
anim();
window.addEventListener('scroll', () => {
box.style.width = `${window.pageYOffset}px`;
if(animState) return;
requestAnimationId = requestAnimationFrame(anim);
animState = true;
});
See the Pen 가속도에 대하여 by YoungMinKim (@oinochoe) on CodePen.