Charts - 애니메이션
Charts - 애니메이션 (Animation)
CSS 기반 및 JavaScript 기반 차트 애니메이션을 모두 사용자 지정하는 방법을 알아봅니다.
본문
MUI X Charts의 일부 요소는 기본적으로 애니메이션됩니다. 예를 들어 Bar Chart의 막대는 축에서 올라오고, Pie Chart의 조각은 원을 채우도록 펼쳐집니다.
이 애니메이션은 주로 CSS로 만들어지지만, 일부는 JavaScript 기반의 React 훅도 사용합니다. 이 훅들을 사용해 기본적으로 애니메이션되지 않는 Charts의 다른 요소를 애니메이션하거나, 자신만의 사용자 지정 컴포넌트에 애니메이션을 추가할 수 있습니다.
Chart 애니메이션을 사용자 지정하려면 특정 사용 사례에 따라 CSS 클래스를 덮어쓰거나 제공된 사용자 지정 훅을 구현해야 할 수 있습니다.
CSS 애니메이션 사용자 지정 (Customizing CSS animations)
기본 CSS 클래스를 덮어써 CSS 기반 애니메이션을 사용자 지정할 수 있습니다. 아래 데모는 라벨의 애니메이션 지속 시간을 2초로 늘리는 방법을 보여 줍니다:
import * as React from 'react';
import { pieClasses, PieChart } from '@mui/x-charts/PieChart';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
const data = [
{ id: 0, value: 10, label: 'series A' },
{ id: 1, value: 15, label: 'series B' },
{ id: 2, value: 20, label: 'series C' },
];
export default function CSSAnimationCustomization() {
const [key, rerender] = React.useReducer((x) => x + 1, 0);
return (
<Stack>
<PieChart
key={key}
series={[{ data, arcLabel: (item) => `${item.value}` }]}
width={200}
height={200}
hideLegend
sx={{
[`& .${pieClasses.arcLabel}.${pieClasses.animate}`]: {
animationDuration: '2s',
},
}}
/>
<Button onClick={() => rerender()}>Restart Animation</Button>
</Stack>
);
}
JavaScript 애니메이션 사용자 지정 (Customizing JavaScript animations)
JavaScript 기반 애니메이션을 덮어쓰거나—사용자 지정 컴포넌트에서 Chart 애니메이션을 사용하려면—사용자 지정 애니메이션 훅을 사용할 수 있습니다.
Charts 패키지는 다음과 같은 애니메이션 훅을 제공합니다:
useAnimateArea()useAnimateBar()useAnimateBarLabel()useAnimateLine()useAnimatePieArc()useAnimatePieArcLabel()
아래 데모는 막대 라벨을 막대 애니메이션에 맞춰 애니메이션해 이 훅들을 사용하는 방법을 보여 줍니다—Run Animation을 클릭해 직접 확인하세요:
import { BarChart, BarLabelProps } from '@mui/x-charts/BarChart';
import * as React from 'react';
import { useAnimateBarLabel } from '@mui/x-charts/hooks';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { styled } from '@mui/material/styles';
export default function JSDefaultAnimation() {
const [key, animate] = React.useReducer((v) => v + 1, 0);
return (
<Stack>
<BarChart
key={key}
xAxis={[{ data: ['A', 'B', 'C'] }]}
series={[
{
type: 'bar',
data: [5, 17, 11],
barLabel: 'value',
},
{
type: 'bar',
data: [0, 12, 15],
barLabel: 'value',
},
{
type: 'bar',
data: [1, 3, 9],
barLabel: 'value',
},
]}
width={300}
height={400}
slots={{ barLabel: AnimatedBarLabel }}
/>
<Button onClick={() => animate()}>Run Animation</Button>
</Stack>
);
}
const Text = styled('text')(({ theme }) => ({
...theme?.typography?.body2,
stroke: 'none',
fill: (theme.vars || theme)?.palette?.text?.primary,
}));
function AnimatedBarLabel(props: BarLabelProps) {
const {
seriesId,
dataIndex,
color,
isFaded,
isHighlighted,
classes,
xOrigin,
yOrigin,
x,
y,
width,
height,
layout,
skipAnimation,
...otherProps
} = props;
const animatedProps = useAnimateBarLabel({
xOrigin,
x,
yOrigin,
y,
width,
height,
layout,
skipAnimation,
});
return (
<Text
{...otherProps}
textAnchor="middle"
dominantBaseline="central"
{...animatedProps}
/>
);
}
useAnimate() 훅
더 세밀한 애니메이션 사용자 지정을 위해 useAnimate(props, params) 훅을 사용할 수 있습니다.
이 훅은 ref와 애니메이션 대상 요소에 전달할 props를 함께 반환합니다.
props 매개변수가 업데이트될 때마다 이 훅은 이전 값에서 다음 값으로의 보간(interpolation)을 생성합니다.
각 애니메이션 프레임이 로드될 때마다 이 보간 함수를 호출해 중간 상태를 얻고 결과를 애니메이션 대상 요소에 적용합니다.
(속성 업데이트는 성능 향상을 위해 React 라이프사이클을 우회하는 명령형 방식입니다.)
params로 다음 속성을 정의할 수 있습니다:
skip:true이면 새 값을 즉시 적용ref: 이 훅에서 반환되는 ref와 병합할 refinitialProps: 컴포넌트 생성 애니메이션에 사용되는 props; 제공되지 않으면 초기 애니메이션이 없음createInterpolator(): 마지막 props에서 다음 props로의 보간 함수 생성transformProps(): 선택적으로 보간된 props를 다른 형식으로 변환applyProps(): 변환된 props를 요소에 적용
더 자세한 설명은 훅의 JSDoc에서 확인할 수 있습니다.
아래 예제에서 라벨은 해당 막대 위에 배치되고 useAnimate() 훅으로 애니메이션됩니다:
import { BarChart, BarLabelProps } from '@mui/x-charts/BarChart';
import * as React from 'react';
import { useAnimate } from '@mui/x-charts/hooks';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { interpolateObject } from '@mui/x-charts-vendor/d3-interpolate';
export default function JSAnimationCustomization() {
const [key, animate] = React.useReducer((v) => v + 1, 0);
return (
<Stack>
<BarChart
key={key}
xAxis={[{ data: ['A', 'B', 'C'] }]}
series={[
{
type: 'bar',
data: [5, 17, 11],
barLabel: 'value',
},
{
type: 'bar',
data: [0, 12, 15],
barLabel: 'value',
},
{
type: 'bar',
data: [1, 3, 9],
barLabel: 'value',
},
]}
width={300}
height={400}
slots={{ barLabel: AnimatedBarLabel }}
/>
<Button onClick={() => animate()}>Run Animation</Button>
</Stack>
);
}
function AnimatedBarLabel(props: BarLabelProps) {
const {
seriesId,
dataIndex,
color,
isFaded,
isHighlighted,
classes,
xOrigin,
yOrigin,
x,
y,
width,
height,
layout,
skipAnimation,
...otherProps
} = props;
const animatedProps = useAnimate(
{ x: x + width / 2, y: y - 2 },
{
initialProps: { x: x + width / 2, y: yOrigin },
createInterpolator: interpolateObject,
transformProps: (p) => p,
applyProps: (element: SVGTextElement, p) => {
element.setAttribute('x', p.x.toString());
element.setAttribute('y', p.y.toString());
},
skip: skipAnimation,
},
);
return (
<text {...otherProps} fill={color} textAnchor="middle" {...animatedProps} />
);
}
서드파티 애니메이션 라이브러리 (Third-party animation libraries)
기본 Chart 애니메이션을 자신만의 (서드파티) 애니메이션 라이브러리로 완전히 대체할 수 있습니다.
:::warning 서드파티 JavaScript 애니메이션 라이브러리는 특히 많은 데이터 포인트를 렌더링하거나 확대, 강조 같은 상호작용을 활성화할 경우 성능 문제를 일으킬 수 있습니다. 선택한 애니메이션 라이브러리로 차트 성능을 반드시 테스트하세요. :::
React Spring
아래 데모는 React Spring을 통합해 막대 라벨 애니메이션에 바운스 효과를 추가하는 방법을 보여 줍니다:
import { BarChart, BarLabelProps } from '@mui/x-charts/BarChart';
import * as React from 'react';
import { animated, useSpring } from '@react-spring/web';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function ReactSpringAnimationCustomization() {
const [key, animate] = React.useReducer((v) => v + 1, 0);
return (
<Stack>
<BarChart
key={key}
xAxis={[{ data: ['A', 'B', 'C'] }]}
series={[
{
type: 'bar',
data: [5, 17, 11],
barLabel: 'value',
},
{
type: 'bar',
data: [0, 12, 15],
barLabel: 'value',
},
{
type: 'bar',
data: [1, 3, 9],
barLabel: 'value',
},
]}
width={300}
height={400}
slots={{ barLabel: AnimatedBarLabel }}
/>
<Button onClick={() => animate()}>Run Animation</Button>
</Stack>
);
}
function AnimatedBarLabel(props: BarLabelProps) {
const {
seriesId,
dataIndex,
color,
isFaded,
isHighlighted,
classes,
xOrigin,
yOrigin,
x,
y,
width,
height,
layout,
skipAnimation,
...otherProps
} = props;
const style = useSpring({
from: { y: yOrigin },
to: { y: y - 4 },
config: { tension: 100, friction: 10 },
});
return (
<animated.text
{...otherProps}
// @ts-ignore
fill={color}
x={xOrigin + x + width / 2}
width={width}
height={height}
style={style}
textAnchor="middle"
/>
);
}
Motion
다음 데모는 Motion 라이브러리를 사용해 차트의 점과 선에 페이드인 효과를 적용합니다:
import {
LineChart,
type AnimatedLineProps,
type MarkElementProps,
} from '@mui/x-charts/LineChart';
import * as React from 'react';
import { motion } from 'motion/react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function MotionAnimationCustomization() {
const [key, animate] = React.useReducer((v) => v + 1, 0);
return (
<Stack>
<LineChart
key={key}
xAxis={[{ data: [1, 2, 3, 5, 8, 10] }]}
series={[
{
data: [2, 5.5, 2, 8.5, 1.5, 5],
curve: 'linear',
},
{
data: [3, 4, 6, 7, 9, 11],
curve: 'linear',
},
]}
width={500}
height={300}
slots={{
line: AnimatedLine,
mark: AnimatedMark,
}}
/>
<Button onClick={() => animate()}>Run Animation</Button>
</Stack>
);
}
function AnimatedLine({ d, ownerState, skipAnimation }: AnimatedLineProps) {
return (
<motion.path
d={d}
fill="transparent"
stroke={ownerState.color}
initial={{
opacity: skipAnimation ? 1 : 0,
}}
animate={{ opacity: 1 }}
transition={{ duration: 1.5, ease: 'easeInOut' }}
/>
);
}
function AnimatedMark({ x, y, color, skipAnimation }: MarkElementProps) {
return (
<motion.circle
cx={x}
cy={y}
r={5}
fill={color}
initial={{
scale: skipAnimation ? 1 : 0,
opacity: skipAnimation ? 1 : 0,
}}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 1, delay: 0.5, ease: 'backOut' }}
/>
);
}