Animation
Shoelace의 Animation 컴포넌트(sl-animation)는 요소를 선언적으로(declaratively) 애니메이션할 수 있게 해주는 컴포넌트예요. 거의 100가지가 내장된 프리셋(preset)을 바로 쓸 수도 있고, 커스텀 keyframes로 직접 만들 수도 있답니다. 내부적으로는 Web Animations API를 사용해요.
출처: 문서
본문
거의 100가지가 내장된 프리셋(preset)으로 요소를 선언적으로 애니메이션할 수 있고, 커스텀 keyframes로 직접 만들 수도 있어요. Web Animations API를 기반으로 동작해요.
요소를 애니메이션하려면 그 요소를 <sl-animation>으로 감싸고 animation name을 설정하면 돼요. play 속성(attribute)을 추가하기 전까지는 애니메이션이 시작되지 않아요. 모든 애니메이션 옵션 목록은 properties 표를 참고하세요.
<div class="animation-overview">
<sl-animation name="bounce" duration="2000" play><div class="box"></div></sl-animation>
<sl-animation name="jello" duration="2000" play><div class="box"></div></sl-animation>
<sl-animation name="heartBeat" duration="2000" play><div class="box"></div></sl-animation>
<sl-animation name="flip" duration="2000" play><div class="box"></div></sl-animation>
</div>
<style>
.animation-overview .box {
display: inline-block;
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
margin: 1.5rem;
}
</style>
import SlAnimation from '@shoelace-style/shoelace/dist/react/animation';
const css = `
.animation-overview .box {
display: inline-block;
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
margin: 1.5rem;
}
`;
const App = () => (
<>
<div class="animation-overview">
<SlAnimation name="bounce" duration={2000} play>
<div class="box" />
</SlAnimation>
<SlAnimation name="jello" duration={2000} play>
<div class="box" />
</SlAnimation>
<SlAnimation name="heartBeat" duration={2000} play>
<div class="box" />
</SlAnimation>
<SlAnimation name="flip" duration={2000} play>
<div class="box" />
</SlAnimation>
</div>
<style>{css}</style>
</>
);
애니메이션은 <sl-animation> 안에서 찾은 첫 번째 자식 요소에만 적용돼요.
Examples
Animations & Easings
이 예시는 내장된 애니메이션과 easing을 모두 보여줘요. 애니메이션은 널리 쓰이는 Animate.css 라이브러리를 기반으로 해요.
<div class="animation-sandbox">
<sl-animation name="bounce" easing="ease-in-out" duration="2000" play>
<div class="box"></div>
</sl-animation>
<div class="controls">
<sl-select label="Animation" value="bounce"></sl-select>
<sl-select label="Easing" value="linear"></sl-select>
<sl-input label="Playback Rate" type="number" min="0" max="2" step=".25" value="1"></sl-input>
</div>
</div>
<script type="module">
import { getAnimationNames, getEasingNames } from '/dist/utilities/animation.js';
const container = document.querySelector('.animation-sandbox');
const animation = container.querySelector('sl-animation');
const animationName = container.querySelector('.controls sl-select:nth-child(1)');
const easingName = container.querySelector('.controls sl-select:nth-child(2)');
const playbackRate = container.querySelector('sl-input[type="number"]');
const animations = getAnimationNames();
const easings = getEasingNames();
animations.map(name => {
const option = Object.assign(document.createElement('sl-option'), {
textContent: name,
value: name
});
animationName.appendChild(option);
});
easings.map(name => {
const option = Object.assign(document.createElement('sl-option'), {
textContent: name,
value: name
});
easingName.appendChild(option);
});
animationName.addEventListener('sl-change', () => (animation.name = animationName.value));
easingName.addEventListener('sl-change', () => (animation.easing = easingName.value));
playbackRate.addEventListener('sl-input', () => (animation.playbackRate = playbackRate.value));
</script>
<style>
.animation-sandbox .box {
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
}
.animation-sandbox .controls {
max-width: 300px;
margin-top: 2rem;
}
.animation-sandbox .controls sl-select {
margin-bottom: 1rem;
}
</style>
Using Intersection Observer
Intersection Observer를 사용해서 요소가 뷰포트에 들어오거나 나갈 때 애니메이션을 제어할 수 있어요. 예를 들어 아래 박스를 화면 안팎으로 스크롤해 보세요. 박스가 뷰포트에서 벗어나면 애니메이션이 멈추고, 다시 들어올 때마다 재시작돼요.
<div class="animation-scroll">
<sl-animation name="jackInTheBox" duration="2000" iterations="1"><div class="box"></div></sl-animation>
</div>
<script>
const container = document.querySelector('.animation-scroll');
const animation = container.querySelector('sl-animation');
const box = animation.querySelector('.box');
// Watch for the box to enter and exit the viewport. Note that we're observing the box, not the animation element!
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
// Start the animation when the box enters the viewport
animation.play = true;
} else {
animation.play = false;
animation.currentTime = 0;
}
});
observer.observe(box);
</script>
<style>
.animation-scroll .box {
display: inline-block;
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
}
</style>
import { useEffect, useRef, useState } from 'react';
import SlAnimation from '@shoelace-style/shoelace/dist/react/animation';
const css = `
.animation-scroll {
height: calc(100vh + 100px);
}
.animation-scroll .box {
display: inline-block;
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
}
`;
const App = () => {
const animation = useRef(null);
const box = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
animation.current.play = true;
} else {
animation.current.play = false;
animation.current.currentTime = 0;
}
});
if (box.current) {
observer.observe(box.current);
}
}, [box]);
return (
<>
<div class="animation-scroll">
<SlAnimation ref={animation} name="jackInTheBox" duration={2000} iterations={1}>
<div ref={box} class="box" />
</SlAnimation>
</div>
<style>{css}</style>
</>
);
};
Custom Keyframe Formats
자신만의 keyframe formats 을 제공해서 커스텀 애니메이션을 만들 수도 있어요.
<div class="animation-keyframes">
<sl-animation easing="ease-in-out" duration="2000" play>
<div class="box"></div>
</sl-animation>
</div>
<script>
const animation = document.querySelector('.animation-keyframes sl-animation');
animation.keyframes = [
{
offset: 0,
easing: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',
fillMode: 'both',
transformOrigin: 'center center',
transform: 'rotate(0)'
},
{
offset: 1,
easing: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',
fillMode: 'both',
transformOrigin: 'center center',
transform: 'rotate(90deg)'
}
];
</script>
<style>
.animation-keyframes .box {
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
}
</style>
import SlAnimation from '@shoelace-style/shoelace/dist/react/animation';
const css = `
.animation-keyframes .box {
width: 100px;
height: 100px;
background-color: var(--sl-color-primary-600);
}
`;
const App = () => (
<>
<div class="animation-keyframes">
<SlAnimation
easing="ease-in-out"
duration={2000}
play
keyframes={[
{
offset: 0,
easing: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',
fillMode: 'both',
transformOrigin: 'center center',
transform: 'rotate(0)'
},
{
offset: 1,
easing: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',
fillMode: 'both',
transformOrigin: 'center center',
transform: 'rotate(90deg)'
}
]}
>
<div class="box" />
</SlAnimation>
</div>
<style>{css}</style>
</>
);
Playing Animations on Demand
play 속성(attribute)을 적용하기 전까지는 애니메이션이 재생되지 않아요. 처음에는 생략해 두었다가 사용자 상호작용 후처럼 필요할 때 적용할 수 있답니다. 이 예시에서는 버튼을 클릭할 때마다 애니메이션이 한 번씩 재생돼요.
<div class="animation-form">
<sl-animation name="rubberBand" duration="1000" iterations="1">
<sl-button variant="primary">Click me</sl-button>
</sl-animation>
</div>
<script>
const container = document.querySelector('.animation-form');
const animation = container.querySelector('sl-animation');
const button = container.querySelector('sl-button');
button.addEventListener('click', () => {
animation.play = true;
});
</script>
import { useState } from 'react';
import SlAnimation from '@shoelace-style/shoelace/dist/react/animation';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
const App = () => {
const [play, setPlay] = useState(false);
return (
<div class="animation-form">
<SlAnimation name="rubberBand" duration={1000} iterations={1} play={play} onSlFinish={() => setPlay(false)}>
<SlButton variant="primary" onClick={() => setPlay(true)}>
Click me
</SlButton>
</SlAnimation>
</div>
);
};
Importing
autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 무시해도 돼요. 그 외의 경우 아래 스니펫 중 하나를 골라 이 컴포넌트만 골라(cherry pick) 가져올 수 있답니다.
Script / Import / Bundler / React
CDN에서 script 태그로 이 컴포넌트를 가져오려면:
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/animation/animation.js"></script>
CDN에서 JavaScript import로 이 컴포넌트를 가져오려면:
import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/animation/animation.js';
bundler를 사용해 이 컴포넌트를 가져오려면:
import '@shoelace-style/shoelace/dist/components/animation/animation.js';
이 컴포넌트를 React 컴포넌트로 가져오려면:
import SlAnimation from '@shoelace-style/shoelace/dist/react/animation';
Slots
| Name | Description |
|---|---|
| (default) | The element to animate. Avoid slotting in more than one element, as subsequent ones will be ignored. To animate multiple elements, either wrap them in a single container or use multiple <sl-animation> elements. |
슬롯(slots) 사용에 대해 더 알아보기.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
name |
The name of the built-in animation to use. For custom animations, use the keyframes prop. |
string |
'none' |
|
play |
Plays the animation. When omitted, the animation will be paused. This attribute will be automatically removed when the animation finishes or gets canceled. | boolean |
false |
|
delay |
The number of milliseconds to delay the start of the animation. | number |
0 |
|
direction |
Determines the direction of playback as well as the behavior when reaching the end of an iteration. | PlaybackDirection |
'normal' |
|
duration |
The number of milliseconds each iteration of the animation takes to complete. | number |
1000 |
|
easing |
The easing function to use for the animation. This can be a Shoelace easing function or a custom easing function such as cubic-bezier(0, 1, .76, 1.14). |
string |
'linear' |
|
endDelay / end-delay |
The number of milliseconds to delay after the active period of an animation sequence. | number |
0 |
|
fill |
Sets how the animation applies styles to its target before and after its execution. | FillMode |
'auto' |
|
iterations |
The number of iterations to run before the animation completes. Defaults to Infinity, which loops. |
- | Infinity |
|
iterationStart / iteration-start |
The offset at which to start the animation, usually between 0 (start) and 1 (end). | number |
0 |
|
keyframes |
The keyframes to use for the animation. If this is set, name will be ignored. |
Keyframe[] | undefined |
- | |
playbackRate / playback-rate |
Sets the animation’s playback rate. The default is 1, which plays the animation at a normal speed. Setting this to 2, for example, will double the animation’s speed. A negative value can be used to reverse the animation. This value can be changed without causing the animation to restart. |
number |
1 |
|
currentTime |
Gets and sets the current animation time. | CSSNumberish |
- | |
updateComplete |
A read-only promise that resolves when the component has finished updating. |
속성과 프로퍼티(attributes and properties)에 대해 더 알아보기.
Events
| Name | React Event | Description | Event Detail |
|---|---|---|---|
sl-cancel |
onSlCancel |
Emitted when the animation is canceled. | - |
sl-finish |
onSlFinish |
Emitted when the animation finishes. | - |
sl-start |
onSlStart |
Emitted when the animation starts or restarts. | - |
이벤트(events)에 대해 더 알아보기.
Methods
| Name | Description | Arguments |
|---|---|---|
cancel() |
Clears all keyframe effects caused by this animation and aborts its playback. | - |
finish() |
Sets the playback time to the end of the animation corresponding to the current playback direction. | - |
메서드(methods)에 대해 더 알아보기.
더 알아보기 (Learn more)
- Shoelace 시작하기(getting started) — 컴포넌트 설치와 로딩 방법
- Web Animations API (MDN) — 이 컴포넌트가 사용하는 핵심 API
- Animate.css — 내장 애니메이션 프리셋의 근간이 된 라이브러리