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

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

Sprite renderer component.

## Sprite extends Paint

Sprite renderer component.

Example: Draw one cell of a sprite sheet

```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): Constructor.
- `tick(timeDelta)` (method, since 0.2.0): Update.
  - `timeDelta` number: Time since the last frame. (Seconds)
- `isTickNeeded()` (method, since 0.4.0): Whether tick has work to do. (false since it only draws, true if a subclass redefines tick)
  - returns boolean: True if tick has work to do.
- `draw(graphic)` (method, since 0.2.0): Draw.
  - `graphic` Graphic: Graphics.
- `isDrawnInsideContent()` (method, since 0.4.0): 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)
  - returns boolean: True if drawing only inside the content area.
- `writeGeometryKey(geometryKey)` (method, since 0.4.0): 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)
  - `geometryKey` GeometryKey: Key to write the inputs to.
  - returns boolean: True if the inputs were written.
- `setSpriteDrawMode(spriteDrawMode)` (method, since 0.2.0): Sets the sprite draw mode.
  - `spriteDrawMode` string: Draw mode. ("simple", "sliced", "tiled")
- `getSpriteDrawMode()` (method, since 0.2.0): Returns the sprite draw mode.
  - returns string: Draw mode. ("simple", "sliced", "tiled")
- `setSpriteBlendMode(spriteBlendMode)` (method, since 0.2.0): Sets the sprite blend mode.
  - `spriteBlendMode` string: Blend mode. (a Canvas2D globalCompositeOperation name, initially "source-over")
- `getSpriteBlendMode()` (method, since 0.2.0): Returns the sprite blend mode.
  - returns string: Blend mode. (a Canvas2D globalCompositeOperation name)
- `setNineSlice(nineSlice)` (method, since 0.2.0): Sets the nine-slice region.
  - `nineSlice` Rect: Nine slice borders. (position.x left, position.y top, size.x right, size.y bottom thickness, pixels, used by "sliced")

  Example: Stretch with nine slice

  ```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 the nine-slice region.
  - returns Rect: Nine slice borders.
- `setImage(image)` (method, since 0.2.0): Sets the image.
  - `image` HTMLImageElement | HTMLCanvasElement | OffscreenCanvas | ImageAsset: Image. (a drawable source such as HTMLImageElement, HTMLCanvasElement, OffscreenCanvas, or an ImageAsset, cleared if null or undefined, other types are ignored)

  Example: Using what was drawn on a canvas as a sprite

  ```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 the image.
  - returns HTMLImageElement | HTMLCanvasElement | OffscreenCanvas: Image. (null if none)
- `setImagePath(imagePath)` (method, since 0.4.0): Sets the image path. (Only records it and does not load the image, UIDocument writes and reads this path instead of the image)
  - `imagePath` string: Image path.
- `getImagePath()` (method, since 0.4.0): Returns the image path. (empty string if not set)
  - returns string: Image path. (empty string if not set)

  Example: Recording an image path and reading it back

  ```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): Sets a piece. (sets the Frame's image and its inner region together, clears the image if null, SpriteAtlas.readFrame)
  - `frame` Frame | null: Frame to set. (clears the image if null)

  Example: Set a piece with a 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): Sets the image region.
  - `imageRect` Rect: Area of the image to draw. (pixels, the whole image if empty)
- `getImageRect()` (method, since 0.2.0): Returns the image region.
  - returns Rect: Area of the image to draw.
- `setHorizontalFlip(flip)` (method, since 0.2.0): Sets whether to flip the image.
  - `flip` boolean: Flips horizontally if true.
- `setVerticalFlip(flip)` (method, since 0.2.0): Sets whether to flip the image.
  - `flip` boolean: Flips vertically if true.
- `isHorizontalFlip()` (method, since 0.2.0): Returns whether the image is flipped.
  - returns Vector2: True if flipped horizontally.
- `isVerticalFlip()` (method, since 0.2.0): Returns whether the image is flipped.
  - returns Vector2: True if flipped vertically.
- `getFlip()` (method, since 0.2.0): Returns the image flip value.
  - returns Vector2: Flip scale. (-1 on a flipped axis, otherwise 1, a new vector)

## SpriteDrawMode (enum)

Sprite mode.

- `simple` = `simple`: Draws the image region as is.
- `sliced` = `sliced`: Draws as nine slices, corners are not stretched.
- `tiled` = `tiled`: Draws the image repeated like tiles.

## SpriteBlendMode (enum)

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.

- `normal` = `source-over`: Default alpha compositing.
- `sourceIn` = `source-in`: Outputs only the overlapping area (background alpha mask).
- `sourceOut` = `source-out`: Outputs only the area outside the overlap.
- `sourceAtop` = `source-atop`: Composites only the overlapping area over the background.
- `destinationOver` = `destination-over`: Composites under the background.
- `destinationIn` = `destination-in`: Keeps only the overlapping area of the background.
- `destinationOut` = `destination-out`: Keeps only the non-overlapping area of the background.
- `destinationAtop` = `destination-atop`: Keeps only the overlapping area over the background.
- `lighter` = `lighter`: Color addition (Add).
- `copy` = `copy`: Outputs only the source (ignores the background).
- `xor` = `xor`: Excludes the overlapping area.
- `multiply` = `multiply`: Multiply compositing (darkens).
- `screen` = `screen`: Screen compositing (lightens).
- `overlay` = `overlay`: Overlay (emphasizes contrast).
- `darken` = `darken`: Picks the darker pixel.
- `lighten` = `lighten`: Picks the lighter pixel.
- `colorDodge` = `color-dodge`: Color dodge (lightens).
- `colorBurn` = `color-burn`: Color burn (darkens).
- `hardLight` = `hard-light`: Hard light.
- `softLight` = `soft-light`: Soft light.
- `difference` = `difference`: Difference compositing.
- `exclusion` = `exclusion`: Difference compositing (lower contrast).
- `hue` = `hue`: Applies hue only.
- `saturation` = `saturation`: Applies saturation only.
- `color` = `color`: Applies hue and saturation.
- `luminosity` = `luminosity`: Applies luminosity only.
