# core/component/sprite (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/core/component/sprite/

스프라이트 출력자 컴포넌트.

## Sprite extends Paint

스프라이트 출력자 컴포넌트.

예제: 스프라이트 시트의 한 칸 그리기

```js
import { Engine, EngineConfiguration, Scene, Vector2, Rect, WorldNode, Sprite, ImageAsset } from "./build/vanilla.js";

class MainScene extends Scene {
	async load(engine) {
		await super.load(engine);
		const imageAsset = new ImageAsset();
		await imageAsset.load("examples/assets/spritesheet.png");
		const spriteNode = new WorldNode();
		spriteNode.setContentSize(Vector2.create(200, 200));
		spriteNode.setLocalPosition(Vector2.create(320, 180));
		const sprite = spriteNode.addComponent(Sprite);
		sprite.setImage(imageAsset);
		sprite.setImageRect(Rect.create(0, 0, 200, 200));
		sprite.setHorizontalFlip(true);
		const root = this.getRoot();
		root.addChild(spriteNode);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.2.0): 생성.
- `tick(timeDelta)` (method, since 0.2.0): 갱신.
  - `timeDelta` number: 지난 프레임부터의 시간. (초)
- `isTickNeeded()` (method, since 0.4.0): tick 이 할 일이 있는지. (그리기만 하므로 거짓, 하위 클래스가 tick 을 다시 정의하면 참)
  - returns boolean: tick 이 할 일이 있으면 참.
- `draw(graphic)` (method, since 0.2.0): 출력.
  - `graphic` Graphic: 그래픽.
- `isDrawnInsideContent()` (method, since 0.4.0): 내용 영역 안에서만 그리는지 반환.
  - 조각, 나인 슬라이스, 타일 모두 내용 영역 안에 그리고, 뒤집어도 영역 안에서 뒤집으므로 true.
  - draw 를 덮어쓴 하위 클래스는 어디에 그리는지 모르므로 false. (그 클래스가 이 함수도 덮어써 알린다)
  - returns boolean: 내용 영역 안에서만 그리면 참.
- `writeGeometryKey(geometryKey)` (method, since 0.4.0): 그리기 입력을 기하 캐시 열쇠에 적기. (그림과 그 크기, 색, 뒤집기, 그리기 꼴, 섞기, 그림 사각형, 나인 슬라이스, 모서리 반지름, 내용 크기)
  - 그림 크기도 적어, 받는 중이던 그림이 다 받아지면 다시 셈한다.
  - draw 를 덮어쓴 하위 클래스는 무엇을 읽는지 모르므로 false. (그 클래스가 이 함수도 덮어써 알린다)
  - `geometryKey` GeometryKey: 입력을 적을 열쇠.
  - returns boolean: 입력을 적었으면 참.
- `setSpriteDrawMode(spriteDrawMode)` (method, since 0.2.0): 스프라이트 출력 모드 설정.
  - `spriteDrawMode` string: 그리는 방식. ("simple", "sliced", "tiled")
- `getSpriteDrawMode()` (method, since 0.2.0): 스프라이트 출력 모드 반환.
  - returns string: 그리는 방식. ("simple", "sliced", "tiled")
- `setSpriteBlendMode(spriteBlendMode)` (method, since 0.2.0): 스프라이트 블렌드 모드 설정.
  - `spriteBlendMode` string: 섞는 방식. (Canvas2D globalCompositeOperation 이름, 처음은 "source-over")
- `getSpriteBlendMode()` (method, since 0.2.0): 스프라이트 블렌드 모드 반환.
  - returns string: 섞는 방식. (Canvas2D globalCompositeOperation 이름)
- `setNineSlice(nineSlice)` (method, since 0.2.0): 나인슬라이스 영역 설정.
  - `nineSlice` Rect: 나인 슬라이스 경계. (position.x 왼쪽, position.y 위, size.x 오른쪽, size.y 아래 두께, 픽셀, "sliced" 에서 쓴다)

  예제: 나인 슬라이스로 늘려 그리기

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Rect, WorldNode, Sprite, ImageAsset } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const imageAsset = new ImageAsset();
  		await imageAsset.load("assets/icons/icon.png");
  		const panelNode = new WorldNode();
  		panelNode.setContentSize(Vector2.create(300, 120));
  		panelNode.setLocalPosition(Vector2.create(320, 180));
  		const sprite = panelNode.addComponent(Sprite);
  		sprite.setImage(imageAsset);
  		sprite.setSpriteDrawMode("sliced");
  		sprite.setNineSlice(Rect.create(40, 40, 40, 40));
  		const root = this.getRoot();
  		root.addChild(panelNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getNineSlice()` (method, since 0.2.0): 나인슬라이스 영역 반환.
  - returns Rect: 나인 슬라이스 경계.
- `setImage(image)` (method, since 0.2.0): 이미지 설정.
  - `image` HTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageAsset: 그림. (그릴 수 있는 원천인 HTMLImageElement, HTMLCanvasElement, OffscreenCanvas 나 ImageAsset, null 이나 undefined 면 비운다, 그 밖의 꼴은 무시한다)

  예제: 캔버스에 그린 것을 스프라이트로

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, WorldNode, Sprite } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const canvas = document.createElement("canvas");
  		canvas.width = 64;
  		canvas.height = 64;
  		const canvasRenderingContext = canvas.getContext("2d");
  		canvasRenderingContext.fillStyle = "#ff6600";
  		canvasRenderingContext.fillRect(0, 0, 64, 64);
  		const spriteNode = new WorldNode();
  		spriteNode.setContentSize(Vector2.create(128, 128));
  		spriteNode.setLocalPosition(Vector2.create(320, 180));
  		const sprite = spriteNode.addComponent(Sprite);
  		sprite.setImage(canvas);
  		const root = this.getRoot();
  		root.addChild(spriteNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getImage()` (method, since 0.2.0): 이미지 반환.
  - returns HTMLImageElement | HTMLCanvasElement | OffscreenCanvas: 그림. (없으면 null)
- `setImagePath(imagePath)` (method, since 0.4.0): 그림 경로 설정. (적어 두기만 하고 그림을 읽지 않는다, UIDocument 가 그림 대신 이 경로를 적고 읽는다)
  - `imagePath` string: 그림 경로.
- `getImagePath()` (method, since 0.4.0): 그림 경로 반환. (정하지 않았으면 빈 글)
  - returns string: 그림 경로. (정하지 않았으면 빈 글)

  예제: 그림 경로를 적고 다시 읽기

  ```js
  import { Sprite } from "./build/vanilla.js";
  
  const sprite = new Sprite();
  console.log(sprite.getImagePath() === "");
  sprite.setImagePath("images/coin.png");
  console.log(sprite.getImagePath());
  ```

- `setFrame(frame)` (method, since 0.4.0): 조각 걸기. (Frame 의 그림과 그 안의 영역을 함께 건다, null 이면 그림을 비운다, SpriteAtlas.readFrame)
  - `frame` Frame | null: 걸 조각. (null 이면 그림을 비운다)

  예제: Frame 으로 조각 걸기

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Rect, WorldNode, Sprite, Frame, ImageAsset } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const imageAsset = new ImageAsset();
  		await imageAsset.load("examples/assets/spritesheet.png");
  		const frame = new Frame(imageAsset.image, Rect.create(200, 0, 200, 200));
  		const spriteNode = new WorldNode();
  		spriteNode.setContentSize(Vector2.create(200, 200));
  		spriteNode.setLocalPosition(Vector2.create(320, 180));
  		const sprite = spriteNode.addComponent(Sprite);
  		sprite.setFrame(frame);
  		const root = this.getRoot();
  		root.addChild(spriteNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `setImageRect(imageRect)` (method, since 0.2.0): 이미지 영역 설정.
  - `imageRect` Rect: 그림 안에서 그릴 영역. (픽셀, 비어 있으면 그림 전체)
- `getImageRect()` (method, since 0.2.0): 이미지 영역 반환.
  - returns Rect: 그림 안에서 그릴 영역.
- `setHorizontalFlip(flip)` (method, since 0.2.0): 이미지 뒤집기 여부 설정.
  - `flip` boolean: 참이면 좌우로 뒤집는다.
- `setVerticalFlip(flip)` (method, since 0.2.0): 이미지 뒤집기 여부 설정.
  - `flip` boolean: 참이면 위아래로 뒤집는다.
- `isHorizontalFlip()` (method, since 0.2.0): 이미지 뒤집기 여부 반환.
  - returns Vector2: 좌우로 뒤집었으면 참.
- `isVerticalFlip()` (method, since 0.2.0): 이미지 뒤집기 여부 반환.
  - returns Vector2: 위아래로 뒤집었으면 참.
- `getFlip()` (method, since 0.2.0): 이미지 뒤집히는 값 반환.
  - returns Vector2: 뒤집기 배율. (뒤집은 축은 -1, 아니면 1, 새 벡터)

## SpriteDrawMode (enum)

스프라이트 모드.

- `simple` = `simple`: 이미지 영역을 그대로 그린다.
- `sliced` = `sliced`: 아홉 조각으로 잘라 모서리는 늘리지 않고 그린다.
- `tiled` = `tiled`: 이미지를 타일처럼 반복해 그린다.

## SpriteBlendMode (enum)

스프라이트 블렌드 모드. (Canvas2D globalCompositeOperation 대응)
- 26 가지 모두 Graphic.setBlendMode 가 그린다. 포터 더프 연산자, lighter, multiply, screen 은 고정 블렌딩,
  overlay 부터 luminosity 까지 13 가지는 그릴 영역 아래를 떠 와 셰이더로 섞는다. (W3C Compositing and Blending Level 1 공식, 그리기마다 영역 복사가 들고 묶어 그리지 않는다)
- Canvas2D 는 source-in, source-out, destination-in, destination-atop, copy 가 그린 도형 밖(자르기 안 전체)도 지우지만, Graphic 은 그린 도형 안만 바꾼다.

- `normal` = `source-over`: 기본 알파 합성.
- `sourceIn` = `source-in`: 교차 영역만 출력 (배경 알파 마스크).
- `sourceOut` = `source-out`: 교차 외 영역만 출력.
- `sourceAtop` = `source-atop`: 배경 위에 교차 영역만 합성.
- `destinationOver` = `destination-over`: 배경 아래에 합성.
- `destinationIn` = `destination-in`: 배경에서 교차 영역만 유지.
- `destinationOut` = `destination-out`: 배경에서 교차 외 영역만 유지.
- `destinationAtop` = `destination-atop`: 배경 위에 교차 영역만 유지.
- `lighter` = `lighter`: 색상 덧셈 (Add).
- `copy` = `copy`: 소스만 출력 (배경 무시).
- `xor` = `xor`: 교차 영역 제외.
- `multiply` = `multiply`: 곱셈 합성 (어두워짐).
- `screen` = `screen`: 스크린 합성 (밝아짐).
- `overlay` = `overlay`: 오버레이 (명암 강조).
- `darken` = `darken`: 어두운 픽셀 선택.
- `lighten` = `lighten`: 밝은 픽셀 선택.
- `colorDodge` = `color-dodge`: 컬러 닷지 (밝아짐).
- `colorBurn` = `color-burn`: 컬러 번 (어두워짐).
- `hardLight` = `hard-light`: 하드 라이트.
- `softLight` = `soft-light`: 소프트 라이트.
- `difference` = `difference`: 차이값 합성.
- `exclusion` = `exclusion`: 차이값 합성 (낮은 대비).
- `hue` = `hue`: 색조만 적용.
- `saturation` = `saturation`: 채도만 적용.
- `color` = `color`: 색조+채도 적용.
- `luminosity` = `luminosity`: 밝기만 적용.
