import Bounds from "../../game/vector/bounds.js"; import Vec2 from "../../game/vector/vec2.js"; /** * @module SpritePartition * @fileoverview Contains SpritePartition class. */ /** * @class * Partitioned (clipped) area of a sprite for drawing. */ class SpritePartition { /** * Create a new sprite partition. * @param {Sprite} sprite Sprite to clip from * @param {Bounds} bounds Bounds of clipped area * @constructor */ constructor({ sprite = null, bounds = null } = {}) { this._sprite = sprite; this._bounds = bounds; if (this._bounds === null) this._bounds = new Bounds(new Vec2(), new Vec2(this._sprite.width, this._sprite.height)); } /** * Get a copy of the sprite partition. * @returns {SpritePartition} Copied sprite partition */ copy() { return new SpritePartition({ sprite: this._sprite, bounds: this._bounds.copy() }); } // // Getters // /** * Get the width of the sprite. * @returns {number} Width of sprite */ get width() { return this._bounds.width; } /** * Get the height of the sprite. * @returns {number} Height of sprite */ get height() { return this._bounds.height; } // // 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._sprite.image, this._bounds.min.x + 0.1, this._bounds.min.y + 0.1, this._bounds.width - 0.1, this._bounds.height - 0.1, pos.x, pos.y, size.x, size.y ); } } export default SpritePartition;