Remotion 캔들스틱(Candlestick) 애니메이션 제작流程
본 skill은 vibe-motion-app이라는 Remotion 프로젝트에서 S&P 500 K-라인 차트를 생성하는 전체 제작 과정을 기록합니다.
사전 조건
- Remotion 4.0.438 프로젝트, React 19 + TailwindCSS v4 구성
- 플러그인 아키텍처:
motion/에서 scene 정의,remotion/에서 Remotion 합성 파이프라인 처리 - 패키지 매니저로 pnpm 사용
1단계: 금융 데이터 가져오기
Yahoo Finance는 무료로 과거 OHLC 데이터를 제공합니다(API Key 불필요).
scripts/fetch-sp500-data.mjs 파일 생성:
// 핵심: Yahoo Finance Chart API 호출
const url = `https://query1.finance.yahoo.com/v8/finance/chart/%5EGSPC?period1=${PERIOD1}&period2=${PERIOD2}&interval=1wk`;
const resp = await fetch(url);
const json = await resp.json();
const result = json.chart?.result?.[0];
const ts = result.timestamp;
const quote = result.indicators.quote[0];
// { t: timestamp, o: open, h: high, l: low, c: close } 추출
public/data/sp500-weekly.json에 저장하여 Remotion에서 staticFile()을 통해 로드합니다.
매개변수 설명:
%5EGSPC= S&P 500의 Yahoo 심볼 (^GSPCURL 인코딩)interval=1wk= 주간;1d,1mo사용 가능period1/period2= Unix 타임스탬프, 약 40년 범위(1984-2026)
2단계: 플러그인 파일 구조 생성
각 Remotion 플러그인은 4개의 핵심 파일 + 렌더링 프리셋이 필요합니다:
motion/플러그인명/
config.js → 기본 매개변수
timeline.js → scene 컨텍스트 + 프레임별 애니메이션 계산
Scene.jsx → React 컴포넌트(Canvas 드로잉)
plugin.js → 플러그인 등록 객체
render-presets/
default.json → 렌더링 프리셋
2a. config.js — 기본 매개변수
export const DEFAULT_LAYOUT_PARAMS = Object.freeze({
videoWidth: 1920, // 16:9 가로
videoHeight: 1080,
});
export const DEFAULT_ANIMATION_PARAMS = Object.freeze({
durationSeconds: 28, // 애니메이션 총 시간
title: "S&P 500",
subtitle: "지난 40년 · 주간 K-라인 차트",
});
export const DEFAULT_MOTION_PROPS = Object.freeze({
...DEFAULT_LAYOUT_PARAMS,
...DEFAULT_ANIMATION_PARAMS,
});
2b. timeline.js — 애니메이션 로직
세 가지 핵심 함수를 구현해야 합니다:
// 1. scene 컨텍스트: 모든 매개변수 검증 및 강제 형변환
export const resolveXxxSceneContext = (pluginParams) => { ... }
// 2. 시간 계산: durationSeconds * fps
export const getXxxDurationInFrames = ({ fps, sceneContext }) => { ... }
// 3. 프레임별 props: frame/fps에서 progress 등 애니메이션 값 계산
export const buildXxxSceneProps = ({ frame, fps, loop, sceneContext }) => { ... }
핵심 설계 원칙: 모든 애니메이션 상태는 frame 매개변수에만 의존하며, Remotion의 병렬 렌더링 요구 사항을 충족합니다.
2c. Scene.jsx — Canvas 드로잉 컴포넌트
많은 DOM 요소 대신 <canvas>를 사용하여 성능을 향상시킵니다.
데이터 로딩 패턴:
const [dataHandle] = useState(() => delayRender("데이터 로딩 중"));
useEffect(() => {
fetch(staticFile("data/xxx.json"))
.then(r => r.json())
.then(data => { setData(data); continueRender(dataHandle); })
.catch(err => cancelRender(err));
}, [dataHandle]);
Canvas 드로잉 핵심 로직:
const draw = useCallback(() => {
const ctx = canvas.getContext("2d");
const dpr = window.devicePixelRatio || 1;
// 고해상도 화면 대응
canvas.width = W * dpr;
canvas.height = H * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
// 1. 배경 채우기
// 2. 그리드 선 + Y축 가격 눈금
// 3. 캔들 드로잉(wick + body)
// 4. X축 연도 레이블
// 5. 제목/부제목/통계 정보
// 6. 진행 바
}, [data, progress, ...]);
useEffect(() => { draw(); }, [draw]);
캔들 드로잉 핵심 매개변수:
const CANDLE_GAP_RATIO = 0.28; // 캔들 간격 비율
const CANDLE_FADE_FRAMES = 22; // 등장 애니메이션 프레임 수
const MAX_CANDLE_W = 8; // 최대 캔들 너비 (확대/축소 후)
const MIN_CANDLE_W = 0.6; // 최소 캔들 너비
// 보이는 개수에 따라 캔들 너비 자동 조정
const slotW = plotWidth / visibleCount;
const bodyW = Math.max(MIN_CANDLE_W, Math.min(MAX_CANDLE_W * scale, slotW * (1 - GAP_RATIO)));
등장 애니메이션(fade-in + 하단에서 성장):
const appearFrame = (i / (N - 1)) * revealEndFrame;
const candleAge = currentFrame - appearFrame;
const fadeAlpha = Math.min(1, Math.max(0, candleAge / CANDLE_FADE_FRAMES));
// 성장 애니메이션
if (candleAge < CANDLE_FADE_FRAMES && candleAge > 0) {
const growT = easeOutCubic(candleAge / CANDLE_FADE_FRAMES);
displayBodyBottom = lerp(lowY, bodyBottom, growT);
}
ctx.globalAlpha = fadeAlpha;
// ... wick + body 드로잉 ...
ctx.globalAlpha = 1;
다크 테마 색상:
const COLORS = {
bg: "#1a1a19",
grid: "#2c2c2a",
upBorder: "#e66767", // 양봉 테두리 (빨강)
upFill: "rgba(230,103,103,0.15)", // 양뱄 채우기 (반투명)
downFill: "#199e70", // 음봉 채우기 (초록)
textPrimary: "#ffffff",
textSecondary: "#c3c2b7",
textMuted: "#898781",
accent: "#3987e5",
};
2d. plugin.js — 플러그인 등록
export const xxxPlugin = Object.freeze({
id: "플러그인ID",
defaultProps: DEFAULT_MOTION_PROPS,
SceneComponent: XxxScene,
waitForSceneLayoutReady: true, // 데이터 로딩 완료 대기
resolveSceneContext: (params) => ...,
getDurationInFrames: ({ fps, sceneContext }) => ...,
buildSceneProps: ({ frame, fps, loop, sceneContext }) => ...,
getLayout: ({ sceneContext }) => sceneContext.layout,
});
waitForSceneLayoutReady: true는 Scene 컴포넌트가 onAutoLayoutReady()를 호출한 후에야 프레임 렌더링을 시작하도록 보장합니다.
2e. render-presets/default.json
{
"title": "S&P 500",
"subtitle": "지난 40년 · 주간 K-라인 차트",
"videoWidth": 1920,
"videoHeight": 1080,
"durationSeconds": 28
}
3단계: 합성 등록
motion/project.js를 수정하여 ACTIVE_COMPOSITION을 새 플러그인으로 전환합니다:
import { xxxPlugin } from "./xxx/plugin.js";
export const ACTIVE_COMPOSITION = Object.freeze({
id: "SP500Kline",
fps: 30,
plugin: xxxPlugin,
});
4단계: 검증 및 렌더링
# 합성 등록 검증
pnpm run remotion:compositions
# Studio 미리보기 실행 (타임라인 드래그, 매개변수 조정 지원)
pnpm run dev
# 단일 프레임 스크린샷 렌더링
npx remotion still SP500Kline out/frame.png --frame=420
# 전체 비디오 렌더링
npx remotion render SP500Kline out/output.mp4
# 프리셋을 사용한 렌더링
REMOTION_PROPS_FILE=motion/xxx/render-presets/default.json pnpm run remotion:render
##常见 문제
Yahoo Finance API CORS 문제
Remotion 렌더링 환경(Node.js 무헤드 브라우저)에서는 CORS 문제가 발생하지 않습니다.
브라우저 미리보기에서 CORS 문제가 발생하면 staticFile()을 사용하여 미리 가져온 로컬 JSON을 로드하세요.
고 DPI 화면에서 Canvas가 흐릿한 경우
항상 devicePixelRatio를 곱하세요:
canvas.width = W * dpr;
canvas.height = H * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
캔들 개수가 너무 많아 너비가 작아지는 경우
최소 너비 0.6px를 설정하고, slotW < 1일 때 간격 비율을 줄이거나 데이터를 집계하세요.
애니메이션 진행 제어
구간별 이징 함수 사용:
- 시작 3%: 빠르게 기준선 설정
- 중간 90%: 일정하게 표시
- 끝부분: 약간 감속하여 극적인 효과 강화