Skip to content

Sprite

Sprite selects one rectangular region from a Graphic, usually a frame in a sprite sheet, and draws that region at its original size.

const sheet = this.game.images.get('characters');
const idleFrame = new Sprite(sheet, 0, 0, 16, 24);
idleFrame.render(context, 80, 48);
flowchart LR
	A[Graphic sprite sheet] --> B[Source rectangle x y width height]
	B --> C[Sprite]
	D[Destination dx dy] --> E[Draw selected rectangle]
	C --> E
new Sprite(graphic, x, y, width, height);

Defines a source rectangle within graphic.image.

Parameter Description
graphic The Graphic containing the full sheet.
x Horizontal source offset in the sheet; defaults to 0.
y Vertical source offset in the sheet; defaults to 0.
width Width of the source rectangle.
height Height of the source rectangle.

The source coordinates identify pixels in the image; they are not the position where the sprite is drawn on the canvas.

Property Description
graphic The source graphic and browser image.
x, y Source rectangle position in the sprite sheet.
width, height Source rectangle dimensions and rendered destination dimensions.
sprite.render(context, dx, dy);

Draws the selected source rectangle at destination coordinates dx, dy using the sprite’s width and height.

// Source: the second 16 × 24 frame in the top row.
const walkingFrame = new Sprite(sheet, 16, 0, 16, 24);
// Destination: logical canvas position.
walkingFrame.render(context, 80, 48);
  • Images creates and retrieves named graphics.
  • Sprites explains sprite sheets and source rectangles.