vanilladocs
vanillapunch.com
API / resource/assetloader

resource/assetloader

애셋 함께 받기.

Loads assets together.

AssetLoaderextends Object

짝Counterpart: vanilla-engine AssetLoader

애셋 함께 받기.

  • 그림, JSON, 글, 바이너리, 소리, 글꼴, 직접 만든 받기(addTask)를 목록에 넣고 load() 로 한꺼번에 받는다. 동시에 받는 수는 setConcurrency 로 정한다. (하나씩 기다리면 받기와 풀기가 줄지어 늦어진다)
  • 실패한 것도 끝난 것으로 쳐서 멈추지 않는다. 실패는 getFailedList() 에 { path, error } 로 남는다.
  • 진행률은 끝난 수 / 전체 수다. (getProgress, 받은 수 getLoadedCount, 끝난 수 getFinishedCount, 전체 getTotalCount) 바뀔 때마다 setProgressHandler 로 건 함수를, 다 끝나면 setCompleteHandler 로 건 함수를 부른다.
  • 받는 동안 더 넣은 것도 같은 load 가 받는다. (일꾼이 동시에 받는 수보다 적게 돌고 있으면 그만큼 더 띄운다) 다 끝난 뒤 더 넣으면 load() 를 다시 부른다.
  • 쓰기:
const assetLoader = new AssetLoader();
assetLoader.setConcurrency(8);
const titleImageAsset = assetLoader.addImage("assets/title.png");
const stageJsonAsset = assetLoader.addJson("assets/stage.json");
gameScene.trackAssetLoader(assetLoader);     // GameScene 로딩 막대가 진행률을 따라간다
await assetLoader.load();

Loads assets together.

  • Adds images, JSON, text, binary, sounds, fonts and custom loads (addTask) to the list and loads them all at once with load(). The number of concurrent loads is set with setConcurrency. (Waiting for each one in turn delays loading and decoding in a queue)
  • Failed ones also count as finished, so it does not stop. Failures remain in getFailedList() as { path, error }.
  • Progress is finished count / total count. (getProgress, loaded count getLoadedCount, finished count getFinishedCount, total getTotalCount) Calls the function set with setProgressHandler on every change, and the function set with setCompleteHandler when everything is done.
  • Items added while loading are also loaded by the same load. (If fewer workers are running than the concurrency, launches that many more) To add more after everything is done, call load() again.
  • Usage:
const assetLoader = new AssetLoader();
assetLoader.setConcurrency(8);
const titleImageAsset = assetLoader.addImage("assets/title.png");
const stageJsonAsset = assetLoader.addJson("assets/stage.json");
gameScene.trackAssetLoader(assetLoader);     // GameScene loading bar follows the progress
await assetLoader.load();
예제Example그림, JSON, 소리, 글꼴을 함께 받기Fetch an image, JSON, sound and font together
import { AssetLoader } from "./build/vanilla.js";

const assetLoader = new AssetLoader();
assetLoader.setConcurrency(4);
const imageAsset = assetLoader.addImage("examples/assets/spritesheet.png");
const jsonAsset = assetLoader.addJson("examples/timelineshowcase/assets/combo.timeline.json");
const audioAsset = assetLoader.addAudio("examples/assets/beep.wav");
const fontAsset = assetLoader.addFont("DOSGothic", "examples/assets/DOSGothic.woff");
assetLoader.setProgressHandler((progress, finishedCount, totalCount) => {
	console.log(progress, finishedCount, totalCount);
});
const failedList = await assetLoader.load();
console.log(failedList.length, imageAsset.isLoaded(), jsonAsset.isLoaded(), audioAsset.getDuration(), fontAsset.family);
생성자constructorconstructor()#0.4.0 부터since 0.4.0소스source

생성.

Constructor.

짝Counterpart: vanilla-engine AssetLoader.new

메서드methodsetConcurrency(concurrency)#0.4.0 부터since 0.4.0소스source

동시에 받는 수 설정. (1 이상, 소수는 버린다. 받는 중에 바꾸면 다음 load 부터)

Sets the number of concurrent loads. (1 or more, fractions are discarded. If changed while loading, applies from the next load)

concurrencynumber
동시에 받는 수. (유한한 숫자가 아니면 무시한다)Number fetched at the same time. (ignored if not a finite number)

짝Counterpart: vanilla-engine AssetLoader.set_concurrency

메서드methodgetConcurrency()#0.4.0 부터since 0.4.0소스source

동시에 받는 수 반환.

Returns the number of concurrent loads.

반환Returnsnumber 동시에 받는 수. (기본 6)Number fetched at the same time. (default 6)

짝Counterpart: vanilla-engine AssetLoader.get_concurrency

메서드methodaddImage(path)#0.4.0 부터since 0.4.0소스source

그림 넣기.

Adds an image.

pathstring
그림 파일 경로.Image file path.

반환ReturnsImageAsset 넣은 그림 애셋. (load 가 끝나면 읽혀 있다)The added image asset. (loaded once load finishes)

짝Counterpart: vanilla-engine AssetLoader.add_image

메서드methodaddJson(path)#0.4.0 부터since 0.4.0소스source

JSON 넣기.

Adds JSON.

pathstring
JSON 파일 경로.JSON file path.

반환ReturnsJsonAsset 넣은 JSON 애셋.The added JSON asset.

짝Counterpart: vanilla-engine AssetLoader.add_json

메서드methodaddText(path)#0.4.0 부터since 0.4.0소스source

글 넣기.

Adds text.

pathstring
글 파일 경로.Text file path.

반환ReturnsTextAsset 넣은 글 애셋.The added text asset.

짝Counterpart: vanilla-engine AssetLoader.add_text

메서드methodaddBlob(path)#0.4.0 부터since 0.4.0소스source

바이너리 넣기.

Adds binary.

pathstring
파일 경로.File path.

반환ReturnsBlobAsset 넣은 블롭 애셋.The added blob asset.

짝Counterpart: vanilla-engine AssetLoader.add_blob

메서드methodaddAudio(path)#0.4.0 부터since 0.4.0소스source

소리 넣기. (AudioContext 가 없는 브라우저에서는 실패로 친다)

Adds a sound. (Counted as failed in browsers without AudioContext)

pathstring
소리 파일 경로.Sound file path.

반환ReturnsAudioAsset 넣은 소리 애셋.The added sound asset.

짝Counterpart: vanilla-engine AssetLoader.add_audio

메서드methodaddFont(family, path, descriptors)#0.4.0 부터since 0.4.0소스source

글꼴 넣기. (받으면 document.fonts 에 family 이름으로 오른다, FontAsset.loadFont)

Adds a font. (Once loaded, it is registered in document.fonts under the family name, FontAsset.loadFont)

familystring
등록할 글꼴 패밀리 이름.Font family name to register.
pathstring
글꼴 파일 경로.Font file path.
descriptorsobject
FontFace 서술자. (weight, style 등, 없으면 생략)FontFace descriptors. (weight, style, etc, omitted if none)

반환ReturnsFontAsset 넣은 글꼴 애셋.The added font asset.

짝Counterpart: vanilla-engine AssetLoader.add_font

메서드methodaddAsset(asset, path)#0.4.0 부터since 0.4.0소스source

애셋 넣기. (asset.load(path) 로 받는 Asset 파생, 다 받은 뒤 isLoaded() 가 거짓이면 실패로 친다)

Adds an asset. (An Asset subclass loaded with asset.load(path), counted as failed if isLoaded() is false after loading)

assetobject
asset.load(path) 로 받는 애셋.An asset fetched with asset.load(path).
pathstring
받을 경로.Path to fetch.

반환Returnsobject 넣은 애셋.The added asset.

메서드methodaddTask(path, loadFunction)#0.4.0 부터since 0.4.0소스source

직접 만든 받기 넣기. (loadFunction 은 Promise 를 돌려주는 함수, 예외를 내면 실패로 친다)

Adds a custom load. (loadFunction is a function that returns a Promise, counted as failed if it throws)

pathstring
실패 목록과 진행에 보일 이름.Name shown in the failed list and progress.
loadFunction() => Promise<any>
받기 함수. (Promise 를 돌려준다, 거부되면 실패로 친다)Load function. (returns a Promise, counted as a failure if it rejects)
예제Example애셋이 아닌 받기를 함께 받기Fetch something that is not an asset together
import { AssetLoader } from "./build/vanilla.js";

const assetLoader = new AssetLoader();
const timelineList = [];
assetLoader.addTask("logo.timeline.json", async () => {
	const response = await fetch("examples/timelineshowcase/assets/logo.timeline.json");
	const timeline = await response.json();
	timelineList.push(timeline);
});
assetLoader.setCompleteHandler((failedList) => {
	console.log(failedList.length, timelineList.length);
});
await assetLoader.load();
메서드methodaddEntry(path, loadFunction, asset)#0.4.0 부터since 0.4.0소스source

목록에 넣기.

Adds to the list.

pathstring
실패 목록과 진행에 보일 이름.Name shown in the failed list and progress.
loadFunction() => Promise<any>
받기 함수. (Promise 를 돌려준다)Load function. (returns a Promise)
assetobject | null
받은 뒤 isLoaded() 로 성공을 확인할 애셋. (null 이면 확인하지 않는다)Asset whose isLoaded() confirms success after loading. (not checked if null)
메서드methodload()#0.4.0 부터since 0.4.0소스source

받기. (넣은 것을 모두 받을 때까지 기다린다. 실패해도 예외를 내지 않고 실패 목록을 돌려준다)

Loads. (Waits until everything added is loaded. Does not throw on failure and returns the failed list)

반환ReturnsPromise<Array<{ path: string, error: any }>> 다 끝나면 실패 목록으로 풀리는 프로미스. (실패가 없으면 빈 배열, 받는 중에 다시 부르면 같은 프로미스)A promise resolved with the failure list when everything is done. (an empty array if nothing failed, the same promise if called again while loading)

짝Counterpart: vanilla-engine AssetLoader.load

메서드methodasync runWorkers()#0.4.0 부터since 0.4.0소스source

받는 일꾼들 돌리기. (동시에 받는 수만큼 일꾼이 목록의 다음 것을 집어 받는다)

Runs the loading workers. (As many workers as the concurrency pick up and load the next item in the list)

반환ReturnsPromise<Array<object>> 다 끝나면 실패 목록으로 풀리는 프로미스.A promise resolved with the failure list when everything is done.

메서드methodstartWorkers()#0.4.0 부터since 0.4.0소스source

일꾼 띄우기. (돌고 있는 일꾼이 동시에 받는 수보다 적으면, 아직 아무도 집지 않은 것만큼 더 띄운다)

Launches workers. (If fewer workers are running than the concurrency, launches more, as many as the items nobody has picked up yet)

메서드methodasync runWorker()#0.4.0 부터since 0.4.0소스source

일꾼 하나. (목록이 빌 때까지 하나씩 집어 받는다)

One worker. (Picks up and loads items one by one until the list is empty)

반환ReturnsPromise<void> 목록이 비면 풀리는 프로미스.A promise resolved when the list is empty.

메서드methodnotifyProgress()#0.4.0 부터since 0.4.0소스source

진행 알리기.

Notifies progress.

메서드methodsetProgressHandler(progressHandler)#0.4.0 부터since 0.4.0소스source

진행 알림 함수 설정. ((progress, finishedCount, totalCount) => void, null 이면 끔)

Sets the progress handler function. ((progress, finishedCount, totalCount) => void, null turns it off)

progressHandler((progress: number, finishedCount: number, totalCount: number) => void) | null
진행이 바뀔 때마다 진행률(0 ~ 1), 끝난 수, 전체 수를 받는 함수. (null 이면 끔)Function that receives the progress (0 ~ 1), finished count and total count whenever progress changes. (off if null)

짝Counterpart: vanilla-engine AssetLoader.set_progress_handler

메서드methodsetCompleteHandler(completeHandler)#0.4.0 부터since 0.4.0소스source

다 받음 알림 함수 설정. ((failedList) => void, null 이면 끔)

Sets the completion handler function. ((failedList) => void, null turns it off)

completeHandler((failedList: Array<object>) => void) | null
다 끝나면 실패 목록을 받는 함수. (null 이면 끔)Function that receives the failure list when everything is done. (off if null)

짝Counterpart: vanilla-engine AssetLoader.set_complete_handler

메서드methodgetProgress()#0.4.0 부터since 0.4.0소스source

진행률. (끝난 수 / 전체 수, 넣은 것이 없으면 1)

Progress. (Finished count / total count, 1 if nothing was added)

반환Returnsnumber 0 ~ 1

짝Counterpart: vanilla-engine AssetLoader.get_progress

메서드methodgetTotalCount()#0.4.0 부터since 0.4.0소스source

전체 수.

Total count.

반환Returnsnumber 넣은 수.Added count.

짝Counterpart: vanilla-engine AssetLoader.get_total_count

메서드methodgetFinishedCount()#0.4.0 부터since 0.4.0소스source

끝난 수. (받은 것과 실패한 것)

Finished count. (Loaded and failed)

반환Returnsnumber 끝난 수.Finished count.

짝Counterpart: vanilla-engine AssetLoader.get_finished_count

메서드methodgetLoadedCount()#0.4.0 부터since 0.4.0소스source

받은 수. (실패한 것은 빼고)

Loaded count. (Excluding failed)

반환Returnsnumber 받은 수.Loaded count.

짝Counterpart: vanilla-engine AssetLoader.get_loaded_count

메서드methodgetFailedList()#0.4.0 부터since 0.4.0소스source

실패 목록. ({ path, error } 의 복사본)

Failed list. (Copy of { path, error })

반환ReturnsArray<{ path: string, error: any }> 실패 목록의 복사본.A copy of the failure list.

짝Counterpart: vanilla-engine AssetLoader.get_failed_list

메서드methodgetInFlightCount()#0.4.0 부터since 0.4.0소스source

지금 받는 중인 수. (일꾼이 집어 받기 시작했고 아직 끝나지 않은 것)

Number currently loading. (Picked up by a worker and not yet finished)

반환Returnsnumber 받는 중인 수.Count being fetched.

짝Counterpart: vanilla-engine AssetLoader.get_in_flight_count

메서드methodisFinished()#0.4.0 부터since 0.4.0소스source

넣은 것을 모두 받았는지. (실패 포함, 넣은 것이 없으면 true)

Whether everything added has been loaded. (Including failures, true if nothing was added)

반환Returnsboolean 모두 끝났으면 참.True if everything is finished.

짝Counterpart: vanilla-engine AssetLoader.is_finished