animation/timeline
타임라인.
Timeline.
Timelineextends Object
타임라인.
- 문서(서술)는 무대 노드 목록 + 트랙(대상 이름 / 속성 / 키) + 마커로 이루어진 JSON 이며 타임라인 편집기가 저장한다.
- buildStage() 로 무대 노드를 만들거나, bind() 로 기존 노드 트리에 이름으로 붙인다.
- 키의 easing 은 그 키에서 다음 키까지 구간에 적용된다.
- 사용:
const timeline = await Timeline.loadFromUrl("./assets/intro.timeline.json");
timeline.buildStage(stageNode, (imageName) => imageTable[imageName]);
timeline.play();
// 매 프레임: timeline.tick(timeDelta);Timeline.
- The document (description) is JSON made of a stage node list + tracks (target name / property / keys) + markers, and the timeline editor saves it.
- Create the stage nodes with buildStage(), or attach by name to an existing node tree with bind().
- A key's easing applies to the segment from that key to the next key.
- Usage:
const timeline = await Timeline.loadFromUrl("./assets/intro.timeline.json");
timeline.buildStage(stageNode, (imageName) => imageTable[imageName]);
timeline.play();
// every frame: timeline.tick(timeDelta);import { Engine, EngineConfiguration, Scene, Timeline, Vector2 } from "./build/vanilla.js";
const emblemImage = new Image();
emblemImage.src = "examples/timelineshowcase/assets/emblem.png";
await emblemImage.decode();
const timeline = await Timeline.loadFromUrl("examples/timelineshowcase/assets/logo.timeline.json");
timeline.setMarkerHandler((markerName) => {
console.log("marker", markerName);
});
class TimelineScene extends Scene {
async load(engine) {
await super.load(engine);
const root = this.getRoot();
timeline.buildStage(root, (imageName) => {
return imageName === "emblem.png" ? emblemImage : null;
});
timeline.play();
}
tick(timeDelta) {
super.tick(timeDelta);
timeline.tick(timeDelta);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(960, 540);
const engine = new Engine(engineConfiguration);
engine.run(new TimelineScene());
생성.
Constructor.
- descriptionobject | null
- 타임라인 문서. (null 이면 createEmptyDescription 의 빈 문서)Timeline document. (the empty document from createEmptyDescription if null)
짝Counterpart: vanilla-engine Timeline.new
빈 서술 생성. (정적)
Creates an empty description. (static)
반환Returnsobject 빈 타임라인 문서. (3 초, 30 프레임, 반복, 960x540 무대)An empty timeline document. (3 seconds, 30 frames, looping, 960x540 stage)
짝Counterpart: vanilla-engine Timeline.create_empty_description
주소에서 읽기. (정적)
Loads from a URL. (static)
- urlstring
- 타임라인 문서(*.timeline.json) 주소.URL of the timeline document (*.timeline.json).
반환ReturnsPromise<Timeline> 읽은 문서로 만든 타임라인. (실패 응답(404 등)이나 JSON 이 아니면 거부된다)Timeline made from the loaded document. (Rejected for a failed response (404 and so on) or non-JSON)
짝Counterpart: vanilla-engine Timeline.load_from_url
JSON 글에서 만들기. (정적)
Creates from JSON text. (static)
- textstring
- 타임라인 문서 JSON 글.Timeline document JSON text.
반환ReturnsTimeline 만든 타임라인.The created timeline.
짝Counterpart: vanilla-engine Timeline.load_from_text
읽은 JsonAsset 에서 만들기. (정적, 아직 안 읽혔거나 실패했으면 null. 문서는 복사해 쓴다)
Creates from a loaded JsonAsset. (static, null if not loaded yet or failed. The document is copied)
- jsonAssetJsonAsset
- 타임라인 문서를 읽은 JsonAsset.JsonAsset that loaded a timeline document.
반환ReturnsTimeline | null 만든 타임라인. 아직 안 읽혔거나 실패했으면 null.The created timeline. null if not loaded yet or failed.
짝Counterpart: vanilla-engine Timeline.create_from_json_asset
import { JsonAsset, Timeline } from "./build/vanilla.js";
const jsonAsset = new JsonAsset();
await jsonAsset.load("examples/timelineshowcase/assets/title.timeline.json");
const timeline = Timeline.createFromJsonAsset(jsonAsset);
console.log(timeline.getDuration(), timeline.getFrameRate(), timeline.isLoop());ancestorNode 가 node 자신이거나 그 조상인지. (정적)
Whether ancestorNode is node itself or one of its ancestors. (static)
- ancestorNodeWorldNode
- 조상인지 볼 노드.Node to test as an ancestor.
- nodeWorldNode
- 부모를 거슬러 올라갈 노드.Node to walk up the parents from.
반환Returnsboolean ancestorNode 가 node 자신이거나 그 조상이면 참.True if ancestorNode is node itself or one of its ancestors.
무대 노드 한 개 생성. (정적)
Creates a single stage node. (static)
- nodeDescriptionobject
- 무대 노드 서술. (빠진 값은 TIMELINE_NODE_DEFAULTS 로 채운다)Stage node description. (missing values are filled from TIMELINE_NODE_DEFAULTS)
- imageResolverFunction | null
- 이미지 이름을 받아 그림을 돌려주는 함수. (없거나 null 을 돌려주면 data: 주소만 스스로 읽는다)Function that takes an image name and returns an image. (if missing or it returns null, only data: URLs are read on its own)
반환ReturnsWorldNode 서술의 이름을 단 새 노드.A new node named after the description.
짝Counterpart: vanilla-engine Timeline.create_stage_node
노드에 서술 반영. (정적, 편집기가 값을 고칠 때도 쓴다)
Applies the description to a node. (static, also used when the editor changes values)
- nodeWorldNode
- 서술을 반영할 노드. (종류에 맞는 컴포넌트가 없으면 더한다)Node to apply the description to. (adds the component for the type if missing)
- nodeDescriptionobject
- 무대 노드 서술. (빠진 값은 TIMELINE_NODE_DEFAULTS 로 채운다)Stage node description. (missing values are filled from TIMELINE_NODE_DEFAULTS)
- imageResolverFunction | null
- 이미지 이름을 받아 그림을 돌려주는 함수. (없거나 null 을 돌려주면 data: 주소만 스스로 읽는다)Function that takes an image name and returns an image. (if missing or it returns null, only data: URLs are read on its own)
짝Counterpart: vanilla-engine Timeline.apply_stage_node_description
오디오 매니저 설정. (정적, 사운드 노드가 플레이어를 만들 때 쓴다)
Sets the audio manager. (static, used when sound nodes create players)
- audioManagerobject | null
- 사운드 노드가 createAudioPlayer 로 플레이어를 만들 오디오 매니저. (null 이면 만들지 않는다)Audio manager that sound nodes use to create players with createAudioPlayer. (none are created if null)
사운드 노드 정지. (정적, 편집기가 정지 / 되감기 때 부른다)
Stops sound nodes. (static, called by the editor on stop / rewind)
- nodeWorldNode
- 멈출 사운드 노드. (사운드 노드가 아니면 아무것도 하지 않는다)Sound node to stop. (does nothing if it is not a sound node)
짝Counterpart: vanilla-engine Timeline.stop_sound
키 목록에서 시간의 값 표본. (정적, 편집기의 커브 그리기도 쓴다)
Samples the value at a time from a key list. (static, also used for the editor's curve drawing)
- sortedKeysobject[]
- 시간 차례로 정렬한 키 목록. ({ time, value, easing, curve })Key list sorted by time. ({ time, value, easing, curve })
- kindstring
- "number", "color", "string", "boolean" 가운데. (number 와 color 만 보간하고 나머지는 계단)One of "number", "color", "string", "boolean". (only number and color interpolate, the rest step)
- timenumber
- 표본 시간. (초)Sample time. (seconds)
반환Returns* 그 시간의 값. (키가 없으면 number 는 0, 그 밖은 null)Value at that time. (0 for number and null for the rest if there are no keys)
짝Counterpart: vanilla-engine Timeline.sample_keys
트랙의 시간 값 표본. (서술 트랙 그대로, 정렬은 여기서)
Samples a track's value at a time. (the description track as is, sorting is done here)
- trackobject
- 서술의 트랙. (property 로 종류를 정하고, 모르는 속성은 number)A track from the description. (property decides the kind, unknown properties are number)
- timenumber
- 표본 시간. (초)Sample time. (seconds)
반환Returns* 그 시간의 값.Value at that time.
짝Counterpart: vanilla-engine Timeline.sample_track
서술 설정. (참조를 그대로 쓴다, 편집기가 고친 뒤 invalidate() 로 다시 컴파일)
Sets the description. (uses the reference as is, after the editor changes it, recompile with invalidate())
- descriptionobject
- 타임라인 문서. (빠진 stage, tracks, markers 는 채워 넣는다)Timeline document. (missing stage, tracks and markers are filled in)
짝Counterpart: vanilla-engine Timeline.set_description
서술 반환.
Returns the description.
반환Returnsobject 타임라인 문서. (복사본이 아니다)Timeline document. (not a copy)
짝Counterpart: vanilla-engine Timeline.get_description
다시 컴파일 요청. (트랙 / 키가 바뀌었을 때)
Requests recompilation. (when tracks / keys change)
짝Counterpart: vanilla-engine Timeline.invalidate
컴파일. (키를 시간순으로 정렬하고 대상 / 속성 정의를 붙인다)
Compile. (sorts keys by time and attaches target / property definitions)
짝Counterpart: vanilla-engine Timeline.compile
대상 노드의 파티클 시스템 수집. (수동 틱으로 바꿔 타임라인 시간으로만 진행하고, 시드를 줘서 되감을 때마다 같은 결과가 나오게 한다)
Collects the particle systems of target nodes. (switches them to manual tick so they advance only on timeline time, and gives them a seed so every rewind gives the same result)
짝Counterpart: vanilla-engine Timeline.collect_particle_systems
파티클 시간 진행. (재생 중 매 프레임)
Advances particle time. (every frame during playback)
- timeDeltanumber
- 흘릴 시간. (초, 0 이하이면 아무것도 하지 않는다)Time to advance. (seconds, does nothing if 0 or less)
짝Counterpart: vanilla-engine Timeline.simulate_particles
파티클 재시뮬레이션. (스크럽 / 되감기, 비운 뒤 0초부터 이벤트를 다시 밟으며 진행)
Re-simulates particles. (scrub / rewind, clears them and advances from 0 seconds, stepping through the events again)
- timenumber
- 맞출 타임라인 시간. (초)Timeline time to match. (seconds)
짝Counterpart: vanilla-engine Timeline.resimulate_particles
대상 해석. (무대 노드 표 → 사용자 해석기)
Resolves a target. (stage node table → user resolver)
- targetNamestring
- 트랙의 대상 이름.Target name of the track.
반환Returnsobject | null 찾은 대상. 없으면 null.The found target. null if none.
짝Counterpart: vanilla-engine Timeline.resolve_target
대상 해석기 설정. (이름 → 객체. 노드가 아니어도 setTimelineProperty(이름, 값) 이 있으면 된다)
Sets the target resolver. (name → object. It need not be a node, as long as it has setTimelineProperty(name, value))
- targetResolverFunction | null
- 대상 이름을 받아 객체를 돌려주는 함수. (null 이면 끈다)Function that takes a target name and returns an object. (off if null)
짝Counterpart: vanilla-engine Timeline.set_target_resolver
대상 직접 등록.
Registers a target directly.
- targetNamestring
- 트랙의 대상 이름.Target name of the track.
- targetobject
- 노드, 또는 setTimelineProperty(이름, 값) 이 있는 객체.A node, or an object with setTimelineProperty(name, value).
짝Counterpart: vanilla-engine Timeline.set_target
import { Timeline } from "./build/vanilla.js";
const description = Timeline.createEmptyDescription();
description.duration = 2;
description.loop = false;
description.tracks.push({
target: "meter",
property: "level",
keys: [
{ time: 0, value: 0, easing: "quadratic.out" },
{ time: 2, value: 100 }
]
});
const timeline = new Timeline(description);
const meter = { level: 0 };
meter.setTimelineProperty = (name, value) => {
meter[name] = value;
};
timeline.setTarget("meter", meter);
timeline.seek(1);
console.log(timeline.getTime(), meter.level);대상 반환.
Returns a target.
- targetNamestring
- 트랙의 대상 이름.Target name of the track.
반환Returnsobject | null 등록된 대상. 없으면 null. (해석기는 보지 않는다)The registered target. null if none. (does not consult the resolver)
짝Counterpart: vanilla-engine Timeline.get_target
노드 트리에 이름으로 붙이기. (무대를 직접 만든 경우)
Attaches by name to a node tree. (when the stage was built manually)
- rootNodeWorldNode
- 이름으로 찾을 노드 트리의 뿌리. (뿌리 자신도 본다. 이미 등록된 이름은 건너뛴다)Root of the node tree to search by name. (the root itself is checked too. Names already registered are skipped)
짝Counterpart: vanilla-engine Timeline.bind
무대 노드 생성. (서술의 stage.nodes 를 노드 트리로 만들고 대상으로 등록)
- 같은 이름의 노드가 둘이면 모두 붙이고, 이름 표에는 뒤의 것이 남는다.
- 부모가 자기 자신이거나 고리가 되면 parentNode 에 붙인다.
Creates the stage nodes. (builds the description's stage.nodes into a node tree and registers them as targets)
- If two nodes share a name, both are attached, and the latter remains in the name table.
- If the parent is itself or forms a cycle, it is attached to parentNode.
- parentNodeWorldNode
- 무대 노드를 붙일 부모 노드. (서술에 부모가 없는 노드가 여기 붙는다)Parent node for the stage nodes. (nodes without a parent in the description are attached here)
- imageResolverFunction | null
- (이미지 이름) → HTMLImageElement | HTMLCanvasElement | null(image name) → HTMLImageElement | HTMLCanvasElement | null
반환ReturnsSystem.Map 이름 → 노드name → node
짝Counterpart: vanilla-engine Timeline.build_stage
시간 이동. (이벤트는 발생하지 않는다)
Moves to a time. (events are not fired)
- timenumber
- 옮길 시간. (초, 0 ~ 길이로 자른다)Time to move to. (seconds, clamped to 0 ~ duration)
짝Counterpart: vanilla-engine Timeline.seek
갱신. (시간을 흘리고 값을 적용, 지나친 이벤트 / 마커를 발생)
Update. (advances time and applies values, fires passed events / markers)
- timeDeltanumber
- 지난 프레임부터의 시간. (초, 속도를 곱해 흘린다. 재생 중이 아니면 아무것도 하지 않는다)Time since the last frame. (seconds, multiplied by the speed. Does nothing unless playing)
짝Counterpart: vanilla-engine Timeline.tick
import { Timeline } from "./build/vanilla.js";
const description = Timeline.createEmptyDescription();
description.duration = 1;
description.loop = false;
description.tracks.push({
target: "hero",
property: "event",
keys: [
{ time: 0.5, value: "jump" }
]
});
description.markers.push({ time: 0.25, name: "quarter" });
const timeline = new Timeline(description);
timeline.setEventHandler((targetName, eventName) => {
console.log("event", targetName, eventName);
});
timeline.setMarkerHandler((markerName) => {
console.log("marker", markerName);
});
timeline.setCompleteHandler(() => {
console.log("complete", timeline.getTime());
});
timeline.play();
for (let frame = 0; frame < 40; ++frame) {
timeline.tick(1 / 30);
}구간 안의 이벤트 키 / 마커 발생. (fromTime 초과 ~ toTime 이하)
Fires event keys / markers within the interval. (greater than fromTime ~ up to toTime)
- fromTimenumber
- 구간 시작. (초, 이 시간의 키는 넣지 않는다)Start of the range. (seconds, keys at this time are excluded)
- toTimenumber
- 구간 끝. (초, 이 시간의 키는 넣는다)End of the range. (seconds, keys at this time are included)
짝Counterpart: vanilla-engine Timeline.fire_events_between
이벤트 키 처리. (파티클 대상은 play / stop / emit:N 을 스스로 처리, 그 외는 핸들러)
Handles an event key. (particle targets handle play / stop / emit:N themselves, others go to the handler)
- compiledTrackobject
- 컴파일한 이벤트 트랙. (target 과 track 을 쓴다)Compiled event track. (uses target and track)
- keyobject
- 이벤트 키. (value 가 이벤트 이름)Event key. (value is the event name)
- isSilentboolean
- 재시뮬레이션용. (사운드 / 사용자 핸들러는 부르지 않고 파티클만)For re-simulation. (does not call sound / user handlers, particles only)
시간의 값 적용. (연속 속성만, 이벤트는 tick 에서만 발생)
Applies the values at a time. (continuous properties only, events fire only in tick)
- timenumber
- 값을 적용할 시간. (초)Time whose values are applied. (seconds)
짝Counterpart: vanilla-engine Timeline.evaluate
시간 반환.
Returns the time.
반환Returnsnumber 지금 시간. (초)Current time. (seconds)
짝Counterpart: vanilla-engine Timeline.get_time
재생 중 여부 반환.
Returns whether it is playing.
반환Returnsboolean 재생 중이면 참.True if playing.
짝Counterpart: vanilla-engine Timeline.is_playing
속도 설정. (1 = 실시간)
Sets the speed. (1 = real time)
- speednumber
- 재생 속도 배율. (1 = 실시간, 음수면 0 초에서 멈춰 선다)Playback speed factor. (1 = real time, negative values stop at 0 seconds)
짝Counterpart: vanilla-engine Timeline.set_speed
속도 반환.
Returns the speed.
반환Returnsnumber 재생 속도 배율.Playback speed factor.
짝Counterpart: vanilla-engine Timeline.get_speed
반복 설정.
Sets looping.
- isLoopboolean
- 반복하면 참. (문서의 loop 에 쓴다)True to loop. (written to the document's loop)
짝Counterpart: vanilla-engine Timeline.set_loop
반복 여부 반환.
Returns whether it loops.
반환Returnsboolean 문서의 loop 가 true 면 참.True if the document's loop is true.
짝Counterpart: vanilla-engine Timeline.is_loop
길이 반환. (초)
Returns the duration. (seconds)
반환Returnsnumber 길이. (초, 문서 값이 양수가 아니면 0)Duration. (seconds, 0 if the document value is not positive)
짝Counterpart: vanilla-engine Timeline.get_duration
초당 프레임 반환.
Returns the frames per second.
반환Returnsnumber 초당 프레임. (문서 값이 양수가 아니면 30)Frames per second. (30 if the document value is not positive)
짝Counterpart: vanilla-engine Timeline.get_frame_rate
이벤트 핸들러 설정. ((대상 이름, 이벤트 이름, 키, 타임라인))
Sets the event handler. ((target name, event name, key, timeline))
- eventHandlerFunction | null
- (대상 이름, 이벤트 이름, 키, 타임라인) 을 받는 함수. (null 이면 끈다)Function that receives (target name, event name, key, timeline). (off if null)
짝Counterpart: vanilla-engine Timeline.set_event_handler
마커 핸들러 설정. ((마커 이름, 마커, 타임라인))
Sets the marker handler. ((marker name, marker, timeline))
- markerHandlerFunction | null
- (마커 이름, 마커, 타임라인) 을 받는 함수. (null 이면 끈다)Function that receives (marker name, marker, timeline). (off if null)
짝Counterpart: vanilla-engine Timeline.set_marker_handler
완료 핸들러 설정. (반복이 아닐 때 끝에 닿으면)
Sets the completion handler. (when reaching the end while not looping)
- completeHandlerFunction | null
- 타임라인을 받는 함수. (null 이면 끈다)Function that receives the timeline. (off if null)
짝Counterpart: vanilla-engine Timeline.set_complete_handler
함수Functions
3차 베지어 이징 생성. (CSS cubic-bezier 와 같은 제어점, x 는 0 ~ 1)
Creates a cubic Bezier easing. (same control points as CSS cubic-bezier, x is 0 ~ 1)
- x1number
- 첫 제어점 x. (0 ~ 1 로 자른다)x of the first control point. (clamped to 0 ~ 1)
- y1number
- 첫 제어점 y.y of the first control point.
- x2number
- 둘째 제어점 x. (0 ~ 1 로 자른다)x of the second control point. (clamped to 0 ~ 1)
- y2number
- 둘째 제어점 y.y of the second control point.
반환ReturnsFunction 0 ~ 1 진행률을 받아 이징한 값을 돌려주는 함수.Function that takes 0 ~ 1 progress and returns the eased value.
짝Counterpart: vanilla-engine create_bezier_easing
이징 함수 반환. (모르는 이름은 linear, "bezier" 는 curve [x1, y1, x2, y2] 를 쓴다)
Returns an easing function. (unknown names give linear, "bezier" uses curve [x1, y1, x2, y2])
- easingNamestring
- 이징 이름. (TIMELINE_EASING_NAMES 가운데, 비었으면 linear)Easing name. (one of TIMELINE_EASING_NAMES, linear if empty)
- curvenumber[] | null
- "bezier" 의 [x1, y1, x2, y2]. (넷이 안 되면 [0.42, 0, 0.58, 1])[x1, y1, x2, y2] for "bezier". ([0.42, 0, 0.58, 1] if fewer than four)
반환ReturnsFunction 0 ~ 1 진행률을 받아 이징한 값을 돌려주는 함수.Function that takes 0 ~ 1 progress and returns the eased value.
짝Counterpart: vanilla-engine resolve_timeline_easing
import { resolveTimelineEasing, createBezierEasing } from "./build/vanilla.js";
const bounceOut = resolveTimelineEasing("bounce.out");
const customCurve = resolveTimelineEasing("bezier", [0.25, 0.1, 0.25, 1]);
const easeInOut = createBezierEasing(0.42, 0, 0.58, 1);
console.log(bounceOut(0.5), customCurve(0.5), easeInOut(0.25));색 문자열 ↔ 채널.
Color string ↔ channels.
- hexTextstring
- "#rrggbb" 또는 "#rrggbbaa""#rrggbb" or "#rrggbbaa"
반환Returnsnumber[] 0 ~ 1 의 [빨강, 초록, 파랑, 알파]. (읽지 못한 채널은 1)[red, green, blue, alpha] in 0 ~ 1. (1 for channels that cannot be read)
짝Counterpart: vanilla-engine parse_timeline_color
채널을 색 문자열로. ("#rrggbbaa")
Channels to a color string. ("#rrggbbaa")
- channelsnumber[]
- 0 ~ 1 의 [빨강, 초록, 파랑, 알파]. (0 ~ 1 로 자르고, 알파가 없으면 1)[red, green, blue, alpha] in 0 ~ 1. (clamped to 0 ~ 1, alpha is 1 if missing)
반환Returnsstring "#rrggbbaa" 색 문자열."#rrggbbaa" color string.
짝Counterpart: vanilla-engine compose_timeline_color
상수Constants
이징 이름 목록. ("linear" / "step" / "bezier" / "<종류>.<in|out|inOut>")
Easing name list. ("linear" / "step" / "bezier" / "<family>.<in|out|inOut>")
짝Counterpart: vanilla-engine TIMELINE_EASING_NAMES
애니메이션 속성 정의. (이름 → 종류 / 적용 함수)
- kind: "number" 는 이징 보간, "color" 는 채널 보간, "string" / "boolean" 은 계단.
Animated property definitions. (name → kind / apply function)
- kind: "number" uses easing interpolation, "color" uses channel interpolation, "string" / "boolean" step.
짝Counterpart: vanilla-engine TIMELINE_PROPERTY_DEFINITIONS
서술 노드 기본값.
Description node defaults.
짝Counterpart: vanilla-engine TIMELINE_NODE_DEFAULTS