본문 바로가기

그래픽/PixiJS

[Learning Pixi] 5. Loading images into the texture cache

이 글은 다음 페이지를 번역한 글입니다

https://github.com/kittykatattack/learningPixi#loading

 

GitHub - kittykatattack/learningPixi: A step-by-step introduction to making games and interactive media with the Pixi.js renderi

A step-by-step introduction to making games and interactive media with the Pixi.js rendering engine. - GitHub - kittykatattack/learningPixi: A step-by-step introduction to making games and interact...

github.com

 


Pixi는 WebGL을 사용하여 GPU에서 이미지를 렌더링하기 때문에, 이미지는 GPU가 처리할 수 있는 형식이어야 합니다. WebGL 지원 이미지를 텍스처(texture) 라고 합니다. 스프라이트가 이미지를 표시하도록 하려면, 일반 이미지 파일을 WebGL 텍스처로 변환해야 합니다. 모든 것이 내부에서 빠르고 효율적으로 작동하도록 하기 위해ㅡ Pixi는 텍스처 캐시(texture cache) 를 사용하여 스프라이트에 필요한 모든 텍스처를 저장하고 참조합니다. 텍스처의 이름은 참조하는 이미지의 파일 위치와 일치하는 문자열입니다. 즉, "images/cat.png"에서 로드된 텍스처가 있는 경우 다음과 같이 텍스처 캐시에서 찾을 수 있습니다.


PIXI.utils.TextureCache["images/cat.png"];

텍스처는 Pixi의 렌더러가 작업하기에 효율적인 WebGL 호환 형식으로 저장됩니다. 그런 다음 Pixi의 Sprite 클래스를 사용하여 텍스처를 이용한 새 스프라이트를 만들 수 있습니다.


const texture = PIXI.utils.TextureCache["images/anySpriteImage.png"];
const sprite = new PIXI.Sprite(texture);

그런데 이미지 파일을 어떻게 로드하고 텍스처로 변환할끼요? Pixi의 내장 Loader 객체를 사용합니다.


Pixi의 강력한 Loader 객체는 모든 종류의 이미지를 로드하는 데 필요한 모든 것입니다. 다음은 이미지를 로드하고, 이미지 로딩이 완료된 뒤 setup이라는 함수를 호출하는 방법입니다.


PIXI.Loader.shared
  .add("images/anyImage.png")
  .load(setup);

function setup() {
  //This code will run when the loader has finished loading the image
}

Pixi의 개발 팀은 로더를 사용하는 경우 다음과 같이 Loaderresources 객체에서 텍스처를 참조하여 스프라이트를 생성해야 한다고 권장합니다.


const sprite = new PIXI.Sprite(
  PIXI.Loader.shared.resources["images/anyImage.png"].texture
);

다음은 이미지를 로드하고, setup 함수를 호출하고, 로드된 이미지로부터 스프라이트를 생성하기 위해 작성할 수 있는 완전한 코드의 예입니다.


PIXI.Loader.shared
  .add("images/anyImage.png")
  .load(setup);

function setup() {
  const sprite = new PIXI.Sprite(
    PIXI.Loader.shared.resources["images/anyImage.png"].texture
  );

}

다음과 같이 연결 가능(chainable)한 add 메서드를 사용하여 여러 이미지를 나열하여 동시에 여러 이미지를 로드할 수 있습니다.


PIXI.Loader.shared
  .add([
    "images/imageOne.png",
    "images/imageTwo.png",
    "images/imageThree.png"
  ])
  .load(setup);

더 나은 방법은 다음과 같이 단일 add 메서드 내에서 배열에 로드하려는 모든 파일을 나열하는 것입니다.


PIXI.Loader.shared
  .add([
    "images/imageOne.png",
    "images/imageTwo.png",
    "images/imageThree.png"
  ])
  .load(setup);

Loader를 사용하면 JSON 파일을 로드할 수도 있습니다. 이것도 앞으로 학습할 것입니다.