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
Section titled “Constructor”new Sprite(graphic, x, y, width, height);Creates a new Sprite instance.
-
Parameters:
graphic(Graphic): An instance of theGraphicclass 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
Spriteinstance. -
Example:
const sprite = new Sprite(graphic, 0, 0, 32, 32);
Properties
Section titled “Properties”graphic(Graphic): TheGraphicinstance 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
Section titled “Methods”render(canvasX, canvasY, [scale])
Section titled “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 withxandyproperties 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