web/vanilla javascript

javascript로 css의 @keyframes 애니메이션 만들기

Trip the light 2023. 5. 17. 01:10

HTML CODE

// animate를 적용할 root element를 만듭니다.
<div id="root"></div>

 

CSS CODE

/* root element에 기본적인 style을 적용합니다. */
#root {
  width: 100px;
  height: 100px;
  background-color: #FF0000;
}

 

JAVASCRIPT CODE

document.getElementById("root").animate(
  [
    // key frames
    { transform: "translateY(0px)" },
    { transform: "translateY(300px)" },
    { transform: "translateY(0)" },
  ],
  {
    // sync options
    duration: 1000,
    iterations: Infinity,
  }
);

 

2022년부터 vanilla javascript에서도 .animate() 메서드를 사용할 수 있게 되었습니다.

Docs:

https://developer.mozilla.org/es/docs/Web/API/Element/animate

 

Element.animate() - Referencia de la API Web | MDN

El método animate() de la interfaz Element es un método abreviado el cual crea un nuevo Animation, aplicado al elemento, luego reproduce la animación. Devuelve la instancia creada de un objeto Animation.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats

 

Keyframe Formats - Web APIs | MDN

Element.animate(), KeyframeEffect(), and KeyframeEffect.setKeyframes() all accept objects formatted to represent a set of keyframes. There are several options to this format, which are explained below.

developer.mozilla.org