Sprite
The Sprite
class represents a subsection of a larger image (often from a sprite sheet) and provides methods to render this subsection onto an HTML5 canvas. It is used to extract and display specific portions of an image, such as individual frames in an animation.
Constructor
new Sprite(graphic, x, y, width, height);
Creates a new Sprite
instance.
-
Parameters:
graphic
(Graphic
): An instance of theGraphic
class that contains the image (sprite sheet) to extract from.x
(number): The x-coordinate of the sprite within the sprite sheet.y
(number): The y-coordinate of the sprite within the sprite sheet.width
(number): The width of the sprite in pixels.height
(number): The height of the sprite in pixels.
-
Returns: A new
Sprite
instance. -
Example:
const sprite = new Sprite(graphic, 0, 0, 32, 32);
Properties
graphic
(Graphic
): TheGraphic
instance containing the sprite sheet image.x
(number
): The x-coordinate of the sprite within the sprite sheet.y
(number
): The y-coordinate of the sprite within the sprite sheet.width
(number
): The width of the sprite.height
(number
): The height of the sprite.
Methods
render(canvasX, canvasY, [scale])
Renders the sprite onto the canvas at the specified coordinates.
-
Parameters:
canvasX
(number): The x-coordinate where the sprite should be drawn on the canvas.canvasY
(number): The y-coordinate where the sprite should be drawn on the canvas.scale
(object, optional): An object withx
andy
properties that defines the scaling factor for the sprite. Defaults to{ x: 1, y: 1 }
for no scaling.
-
Returns:
void
-
Example:
sprite.render(50, 50); // Draws the sprite at (50, 50) with no scalingsprite.render(100, 100, { x: 2, y: 2 }); // Draws the sprite at (100, 100) with double size