vanilladocs
vanillapunch.com
API / core/component/sprite

core/component/sprite

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

Sprite renderer component.

Spriteextends Paint

짝Counterpart: vanilla-engine Sprite

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

Sprite renderer component.

예제Example스프라이트 시트의 한 칸 그리기Draw one cell of a sprite sheet
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());
생성자constructorconstructor()#0.2.0 부터since 0.2.0소스source

생성.

Constructor.

짝Counterpart: vanilla-engine Sprite.new

메서드methodtick(timeDelta)#0.2.0 부터since 0.2.0소스source

갱신.

Update.

timeDeltanumber
지난 프레임부터의 시간. (초)Time since the last frame. (Seconds)
메서드methodisTickNeeded()#0.4.0 부터since 0.4.0소스source

tick 이 할 일이 있는지. (그리기만 하므로 거짓, 하위 클래스가 tick 을 다시 정의하면 참)

Whether tick has work to do. (false since it only draws, true if a subclass redefines tick)

반환Returnsboolean tick 이 할 일이 있으면 참.True if tick has work to do.

메서드methoddraw(graphic)#0.2.0 부터since 0.2.0소스source

출력.

Draw.

graphicGraphic
그래픽.Graphics.
메서드methodisDrawnInsideContent()#0.4.0 부터since 0.4.0소스source

내용 영역 안에서만 그리는지 반환.

  • 조각, 나인 슬라이스, 타일 모두 내용 영역 안에 그리고, 뒤집어도 영역 안에서 뒤집으므로 true.
  • draw 를 덮어쓴 하위 클래스는 어디에 그리는지 모르므로 false. (그 클래스가 이 함수도 덮어써 알린다)

Returns whether it draws only inside the content area.

  • Pieces, nine-slice and tiles are all drawn inside the content area, and flipping mirrors within the area, so true.
  • false for subclasses that override draw, since where they draw is unknown. (that class overrides this function too to report it)

반환Returnsboolean 내용 영역 안에서만 그리면 참.True if drawing only inside the content area.

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

그리기 입력을 기하 캐시 열쇠에 적기. (그림과 그 크기, 색, 뒤집기, 그리기 꼴, 섞기, 그림 사각형, 나인 슬라이스, 모서리 반지름, 내용 크기)

  • 그림 크기도 적어, 받는 중이던 그림이 다 받아지면 다시 셈한다.
  • draw 를 덮어쓴 하위 클래스는 무엇을 읽는지 모르므로 false. (그 클래스가 이 함수도 덮어써 알린다)

Writes the draw inputs to the geometry cache key. (image and its size, color, flips, draw mode, blend, image rect, nine slice, corner radius, content size)

  • The image size is written too, so an image that was still loading is recomputed once it finishes.
  • A subclass that overrides draw returns false because what it reads is unknown. (that class overrides this function too to report them)
geometryKeyGeometryKey
입력을 적을 열쇠.Key to write the inputs to.

반환Returnsboolean 입력을 적었으면 참.True if the inputs were written.

메서드methodsetSpriteDrawMode(spriteDrawMode)#0.2.0 부터since 0.2.0소스source

스프라이트 출력 모드 설정.

Sets the sprite draw mode.

spriteDrawModestring
그리는 방식. ("simple", "sliced", "tiled")Draw mode. ("simple", "sliced", "tiled")

짝Counterpart: vanilla-engine Sprite.set_sprite_draw_mode

메서드methodgetSpriteDrawMode()#0.2.0 부터since 0.2.0소스source

스프라이트 출력 모드 반환.

Returns the sprite draw mode.

반환Returnsstring 그리는 방식. ("simple", "sliced", "tiled")Draw mode. ("simple", "sliced", "tiled")

짝Counterpart: vanilla-engine Sprite.get_sprite_draw_mode

메서드methodsetSpriteBlendMode(spriteBlendMode)#0.2.0 부터since 0.2.0소스source

스프라이트 블렌드 모드 설정.

Sets the sprite blend mode.

spriteBlendModestring
섞는 방식. (Canvas2D globalCompositeOperation 이름, 처음은 "source-over")Blend mode. (a Canvas2D globalCompositeOperation name, initially "source-over")

짝Counterpart: vanilla-engine Sprite.set_sprite_blend_mode

메서드methodgetSpriteBlendMode()#0.2.0 부터since 0.2.0소스source

스프라이트 블렌드 모드 반환.

Returns the sprite blend mode.

반환Returnsstring 섞는 방식. (Canvas2D globalCompositeOperation 이름)Blend mode. (a Canvas2D globalCompositeOperation name)

짝Counterpart: vanilla-engine Sprite.get_sprite_blend_mode

메서드methodsetNineSlice(nineSlice)#0.2.0 부터since 0.2.0소스source

나인슬라이스 영역 설정.

Sets the nine-slice region.

nineSliceRect
나인 슬라이스 경계. (position.x 왼쪽, position.y 위, size.x 오른쪽, size.y 아래 두께, 픽셀, "sliced" 에서 쓴다)Nine slice borders. (position.x left, position.y top, size.x right, size.y bottom thickness, pixels, used by "sliced")

짝Counterpart: vanilla-engine Sprite.set_nine_slice

예제Example나인 슬라이스로 늘려 그리기Stretch with nine slice
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());
메서드methodgetNineSlice()#0.2.0 부터since 0.2.0소스source

나인슬라이스 영역 반환.

Returns the nine-slice region.

반환ReturnsRect 나인 슬라이스 경계.Nine slice borders.

짝Counterpart: vanilla-engine Sprite.get_nine_slice

메서드methodsetImage(image)#0.2.0 부터since 0.2.0소스source

이미지 설정.

Sets the image.

imageHTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageAsset
그림. (그릴 수 있는 원천인 HTMLImageElement, HTMLCanvasElement, OffscreenCanvas 나 ImageAsset, null 이나 undefined 면 비운다, 그 밖의 꼴은 무시한다)Image. (a drawable source such as HTMLImageElement, HTMLCanvasElement, OffscreenCanvas, or an ImageAsset, cleared if null or undefined, other types are ignored)

짝Counterpart: vanilla-engine Sprite.set_image

예제Example캔버스에 그린 것을 스프라이트로Using what was drawn on a canvas as a sprite
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());
메서드methodgetImage()#0.2.0 부터since 0.2.0소스source

이미지 반환.

Returns the image.

반환ReturnsHTMLImageElement | HTMLCanvasElement | OffscreenCanvas 그림. (없으면 null)Image. (null if none)

짝Counterpart: vanilla-engine Sprite.get_image

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

그림 경로 설정. (적어 두기만 하고 그림을 읽지 않는다, UIDocument 가 그림 대신 이 경로를 적고 읽는다)

Sets the image path. (Only records it and does not load the image, UIDocument writes and reads this path instead of the image)

imagePathstring
그림 경로.Image path.

짝Counterpart: vanilla-engine Sprite.set_image_path

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

그림 경로 반환. (정하지 않았으면 빈 글)

Returns the image path. (empty string if not set)

반환Returnsstring 그림 경로. (정하지 않았으면 빈 글)Image path. (empty string if not set)

짝Counterpart: vanilla-engine Sprite.get_image_path

예제Example그림 경로를 적고 다시 읽기Recording an image path and reading it back
import { Sprite } from "./build/vanilla.js";

const sprite = new Sprite();
console.log(sprite.getImagePath() === "");
sprite.setImagePath("images/coin.png");
console.log(sprite.getImagePath());
메서드methodsetFrame(frame)#0.4.0 부터since 0.4.0소스source

조각 걸기. (Frame 의 그림과 그 안의 영역을 함께 건다, null 이면 그림을 비운다, SpriteAtlas.readFrame)

Sets a piece. (sets the Frame's image and its inner region together, clears the image if null, SpriteAtlas.readFrame)

frameFrame | null
걸 조각. (null 이면 그림을 비운다)Frame to set. (clears the image if null)

짝Counterpart: vanilla-engine Sprite.set_frame

예제ExampleFrame 으로 조각 걸기Set a piece with a Frame
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());
메서드methodsetImageRect(imageRect)#0.2.0 부터since 0.2.0소스source

이미지 영역 설정.

Sets the image region.

imageRectRect
그림 안에서 그릴 영역. (픽셀, 비어 있으면 그림 전체)Area of the image to draw. (pixels, the whole image if empty)

짝Counterpart: vanilla-engine Sprite.set_image_rect

메서드methodgetImageRect()#0.2.0 부터since 0.2.0소스source

이미지 영역 반환.

Returns the image region.

반환ReturnsRect 그림 안에서 그릴 영역.Area of the image to draw.

짝Counterpart: vanilla-engine Sprite.get_image_rect

메서드methodsetHorizontalFlip(flip)#0.2.0 부터since 0.2.0소스source

이미지 뒤집기 여부 설정.

Sets whether to flip the image.

flipboolean
참이면 좌우로 뒤집는다.Flips horizontally if true.

짝Counterpart: vanilla-engine Sprite.set_horizontal_flip

메서드methodsetVerticalFlip(flip)#0.2.0 부터since 0.2.0소스source

이미지 뒤집기 여부 설정.

Sets whether to flip the image.

flipboolean
참이면 위아래로 뒤집는다.Flips vertically if true.

짝Counterpart: vanilla-engine Sprite.set_vertical_flip

메서드methodisHorizontalFlip()#0.2.0 부터since 0.2.0소스source

이미지 뒤집기 여부 반환.

Returns whether the image is flipped.

반환ReturnsVector2 좌우로 뒤집었으면 참.True if flipped horizontally.

짝Counterpart: vanilla-engine Sprite.is_horizontal_flip

메서드methodisVerticalFlip()#0.2.0 부터since 0.2.0소스source

이미지 뒤집기 여부 반환.

Returns whether the image is flipped.

반환ReturnsVector2 위아래로 뒤집었으면 참.True if flipped vertically.

짝Counterpart: vanilla-engine Sprite.is_vertical_flip

메서드methodgetFlip()#0.2.0 부터since 0.2.0소스source

이미지 뒤집히는 값 반환.

Returns the image flip value.

반환ReturnsVector2 뒤집기 배율. (뒤집은 축은 -1, 아니면 1, 새 벡터)Flip scale. (-1 on a flipped axis, otherwise 1, a new vector)

짝Counterpart: vanilla-engine Sprite.get_flip

SpriteDrawModeenum

짝Counterpart: vanilla-engine SpriteDrawMode

스프라이트 모드.

Sprite mode.

이름Name값Value설명Description
simplesimple이미지 영역을 그대로 그린다.Draws the image region as is.
slicedsliced아홉 조각으로 잘라 모서리는 늘리지 않고 그린다.Draws as nine slices, corners are not stretched.
tiledtiled이미지를 타일처럼 반복해 그린다.Draws the image repeated like tiles.

SpriteBlendModeenum

짝Counterpart: vanilla-engine SpriteBlendMode

스프라이트 블렌드 모드. (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 은 그린 도형 안만 바꾼다.

Sprite blend mode. (maps to Canvas2D globalCompositeOperation)

  • Graphic.setBlendMode draws all 26. The Porter-Duff operators, lighter, multiply and screen use fixed blending, and the 13 from overlay to luminosity copy the area under the drawing and mix it in a shader. (W3C Compositing and Blending Level 1 formulas, each draw copies the area and is not batched)
  • Canvas2D source-in, source-out, destination-in, destination-atop and copy also clear outside the drawn shape (the whole clip), but Graphic changes only inside the drawn shape.
이름Name값Value설명Description
normalsource-over기본 알파 합성.Default alpha compositing.
sourceInsource-in교차 영역만 출력 (배경 알파 마스크).Outputs only the overlapping area (background alpha mask).
sourceOutsource-out교차 외 영역만 출력.Outputs only the area outside the overlap.
sourceAtopsource-atop배경 위에 교차 영역만 합성.Composites only the overlapping area over the background.
destinationOverdestination-over배경 아래에 합성.Composites under the background.
destinationIndestination-in배경에서 교차 영역만 유지.Keeps only the overlapping area of the background.
destinationOutdestination-out배경에서 교차 외 영역만 유지.Keeps only the non-overlapping area of the background.
destinationAtopdestination-atop배경 위에 교차 영역만 유지.Keeps only the overlapping area over the background.
lighterlighter색상 덧셈 (Add).Color addition (Add).
copycopy소스만 출력 (배경 무시).Outputs only the source (ignores the background).
xorxor교차 영역 제외.Excludes the overlapping area.
multiplymultiply곱셈 합성 (어두워짐).Multiply compositing (darkens).
screenscreen스크린 합성 (밝아짐).Screen compositing (lightens).
overlayoverlay오버레이 (명암 강조).Overlay (emphasizes contrast).
darkendarken어두운 픽셀 선택.Picks the darker pixel.
lightenlighten밝은 픽셀 선택.Picks the lighter pixel.
colorDodgecolor-dodge컬러 닷지 (밝아짐).Color dodge (lightens).
colorBurncolor-burn컬러 번 (어두워짐).Color burn (darkens).
hardLighthard-light하드 라이트.Hard light.
softLightsoft-light소프트 라이트.Soft light.
differencedifference차이값 합성.Difference compositing.
exclusionexclusion차이값 합성 (낮은 대비).Difference compositing (lower contrast).
huehue색조만 적용.Applies hue only.
saturationsaturation채도만 적용.Applies saturation only.
colorcolor색조+채도 적용.Applies hue and saturation.
luminosityluminosity밝기만 적용.Applies luminosity only.