registry_sprite_sprite.js

import Vec2 from "../../game/vector/vec2.js";

/**
 * @module Sprite
 * @fileoverview Contains Sprite class.
 */

/**
 * @class
 * Used for drawing images onto the canvas.
 */
class Sprite {
    /**
     * Create a new sprite.
     * @param {HTMLImageElement} image Image to use for drawing
     * @param {number} width Width of image
     * @param {number} height Height of image
     * @constructor
     */
    constructor(image, width, height) {
        this._image = image;

        this._width = width;
        this._height = height;
    }


    //
    // Getters
    //

    /**
     * Get the width of the sprite.
     * @returns {number} Width of sprite
     */
    get width() {
        return this._width;
    }

    /**
     * Get the height of the sprite.
     * @returns {number} Height of sprite
     */
    get height() {
        return this._height;
    }

    /**
     * Get the image for the sprite.
     * @returns {HTMLImageElement} Image for sprite
     */
    get image() {
        return this._image;
    }


    //
    // Update & Draw
    //

    /**
     * Update the sprite.
     * @param {number} elapsed Time since last update cycle in seconds
     */
    update(elapsed) {}

    /**
     * Draw the sprite.
     * @param {CanvasRenderingContext2D} ctx
     * @param {Vec2} pos Position/offset to draw sprite at
     * @param {Vec2|null} size Custom size of drawn sprite (or null to use default)
     */
    draw(ctx, pos, size = null) {
        if (size === null)
            size = new Vec2(this._width, this._height);

        ctx.drawImage(this._image, pos.x, pos.y, size.x, size.y);
    }
}

export default Sprite;