-
Notifications
You must be signed in to change notification settings - Fork 0
Web Animation API
박수정 edited this page Sep 4, 2024
·
10 revisions
공식 문서
웹 애니메이션 표준 기술(Web Standard)
CSS Animation의 구현을 기반으로 설계된 API로, 자바스크립트로 CSS 애니메이션을 제어할 수 있다.
브라우저 자체적으로 최적화를 진행해서 성능이 좋은 CSS 애니메이션의 장점을 살리면서,
자바스립트로 구현하는 기존 방식의 애니메이션보다 구현도 간편하다.
- 사용자의 입력 등에 반응해서 대화형 애니메이션을 구현할 수도 있고,
- 여러 개의 애니메이션을 동시에 재생하거나 또는 순차적으로 재생할 수도 있다.
- 스크롤을 타임라인처럼 이용해서 스크롤 애니메이션을 구현할 수도 있다.
무엇보다, 외부 라이브러리가 아닌 웹 표준 기술이기 때문에 익혀두면 두고두고 사용할 수 있다.
Promise 이용 가능
- css에서 애니메이션 따로 키프레임 정의하고
js에서 이벤트 바인딩해서 처리하는 것보다 훨씬 깔끔하다.
- 온전히 스크립트를 컨트롤하기 때문에 할 수 있는 일도 훨씬 많다.
- then에서 받는 data는 animations와 동일하다.
반환된 animation 객체를 이용
-
animation.play()
-
animation.pause()
-
animation.playbackRate
-
animation.playState
-
animation.finished
: 끝날 때 -
animation.ready
: 시작할 때
const box = document.querySelector(".box");
const keyframes = [
{ transform: "translateX(0)", opacity: 0 },
{ transform: "translateX(-50px)", opacity: 1, offset: 0.6 },
{ transform: "translateX(200px)", opacity: 0.5 },
];
const options = {
duration: 2000,
easing: "linear",
fill: "forwards",
// iterations: Infinity,
// direction: "alternate",
};
const animations = box.animate(keyframes, options);
// finished: Promise 객체 반환
animations.finished.then((data) => {
animations.ready.then((data) => {
console.log("finished: 애니메이션 종료!");
// console.log("ready: 애니메이션 시작!");
console.log(data === animations);
});
const box = document.querySelector(".box");
const keyframes = [
{ transform: "translateX(0)", opacity: 0 },
{ transform: "translateX(-50px)", opacity: 1, offset: 0.6 },
{ transform: "translateX(200px)", opacity: 0.5 },
];
const options = {
duration: 2000,
easing: "linear",
fill: "forwards",
iterations: Infinity,
direction: "alternate",
};
// 애니메이션 객체 생성자 함수로 생성
new Animation(
// 키프레임 이펙트 생성자 함수 호출
new KeyframeEffect(
// 애니메이션을 적용할 오브젝트
box,
// 키프레임 설정
keyframes,
// 타이밍 관련 옵션
options
)
).play();