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.
'Javascript' 카테고리의 다른 글
Async/Await를 try/catch 없이 사용하기 (0) | 2021.03.01 |
---|---|
[JS] 자바스크립트 좋은 습관 (object, function, array) (0) | 2021.02.07 |
[JS] Snowpack3 - ESM의 시대가 곧 도래합니다. (0) | 2021.01.23 |
[JS] 자바스크립트 프레임워크 내부 파헤치기 4가지 (0) | 2021.01.03 |
ES2020 7가지 새로운 팁 (0) | 2020.06.29 |
댓글