DisplayDriver Class
The DisplayDriver class handles all canvas rendering operations, including loading sprites, clearing the canvas, and drawing game objects.
Under the hood is uses SpriteLoader to load all the sprites.
Example usage
import DisplayDriver from "@/services/display-driver/displayDriver";
async function initGame() { // Select the canvas element const canvas = document.getElementById("gameCanvas") as HTMLCanvasElement;
// Initialize DisplayDriver const displayDriver = new DisplayDriver(canvas);
// Set resolution for the game displayDriver.setResolution(800, 600);
// Load sprites from autoload.json try { await displayDriver.autoLoadSprites(); } catch (error) { console.error("Error loading sprites:", error); return; }
// Clear canvas and set background color to black displayDriver.clear("black");
// Get the player sprite after loading const playerSprite = displayDriver.getSprite("player");
if (playerSprite) { // Example DisplayData for rendering the player at position (100, 200) const playerDisplayData = { sprite: playerSprite, position: { x: 100, y: 200 }, currentSprite: 0, // Assuming the first frame for the sprite sheet };
// Draw the player sprite displayDriver.drawSprite(playerDisplayData); } else { console.error("Player sprite not found."); }}
initGame();Constructor
new DisplayDriver(canvas: HTMLCanvasElement)| Parameter | Type | Description |
|---|---|---|
canvas | HTMLCanvasElement | The canvas element for rendering. |
Methods
setResolution
Sets the canvas resolution dynamically.
| Parameter | Type | Description |
|---|---|---|
width | number | Canvas width in pixels |
height | number | Canvas height in pixels |
Example
displayDriver.setResolution(800, 600);async autoLoadSprites
Automatically loads sprites defined in the autoload.json file.
Description: Fetches and loads all sprites specified in a JSON file located at
/assets/autoload.json.
Example
await displayDriver.autoLoadSprites();getSprite
Retrieves a loaded sprite by its name.
| Parameter | Type | Description |
|---|---|---|
name | string | Name of the sprite |
Example
const playerSprite = displayDriver.getSprite("player");clear
Retrieves a loaded sprite by its name.
| Parameter | Type | Description |
|---|---|---|
color | string | Background color (default: black) |
Example
displayDriver.clear("white");drawSprite
Draws a sprite at a given position using the provided display data.
| Parameter | Type | Description |
|---|---|---|
displayData | DisplayData | Object containing sprite data |
Example
const sprite = displayDriver.getSprite("player");if (sprite) { displayDriver.drawSprite({ sprite, position: { x: 50, y: 100 }, currentSprite: 0, });}Notes
- Dependencies:
- SpriteLoader: Handles loading and managing sprite assets.
- Error Handling:
- Throws errors if sprite loading fails or if the canvas context is unavailable.