(function(PIXI) { var defaultConfig = { numCol: 1, numRow: 1, delay: 100, repeat: -1 } function SpriteSheet(texture, x, y, width, height, config) { PIXI.Graphics.call(this); this.texture = texture; this.x = x || 0; this.y = y || 0; this.w = width || texture.width; this.h = height || texture.height; this.config = Object.assign({}, defaultConfig, config); this._frames = []; this._current = 0; this._row = 0; this._col = 0; this._stoped = false; this._loop = 0; this.init(); }; SpriteSheet.prototype = PIXI.Graphics.prototype; SpriteSheet.prototype.init = function() { this.visible = false; this.beginFill(0x000000, 1); this.drawRect(0, 0, this.width, this.height); this.endFill(); var maskOverlay = new PIXI.Graphics(); maskOverlay.beginFill(0x000000, 1); maskOverlay.drawRect(0, 0, this.w, this.h); maskOverlay.endFill(); this.addChild(maskOverlay); this.mask = maskOverlay; var sprite = this.sprite = new PIXI.Sprite.fromImage(this.texture); this._total = this.config.numCol * this.config.numRow; this.addChild(sprite); } SpriteSheet.prototype._update = function() { var row = this._current; var col = 0; this.sprite.x = -1 * col * this.w; this.sprite.y = -1 * row * this.h; } SpriteSheet.prototype._animate = function() { if (this.config.repeat > 0 && this._loop >= this.config.repeat) { this.visible = false; this.stop(); return; } if (this._current == this._total - 1) { this._loop++; } var now = Date.now(); if (now - this.elaped > this.config.delay) { this._next(); this._update(); this.elaped = now; } this._animation = requestAnimationFrame(this._animate.bind(this)); } SpriteSheet.prototype._next = function() { this._current = (this._current > (this._total - 1)) ? 0 : this._current + 1; } SpriteSheet.prototype.play = function(onStop) { this.elaped = Date.now(); this._current = 0; this._loop = 0; this.visible = true; if (this._animation) { window.cancelAnimationFrame(this._animation); } this._animate(); if (typeof onComplete === 'function') { this._onStop = onStop; } } SpriteSheet.prototype.stop = function() { this.visible = false; if (typeof onComplete === 'function') { this._onStop(); } } PIXI.extras.SpriteSheet = SpriteSheet; }(PIXI));