Skip to content

Instantly share code, notes, and snippets.

@rhernandog
Last active September 21, 2016 04:03
Show Gist options
  • Save rhernandog/6d1a14e647d8a8083503d1d2274d671a to your computer and use it in GitHub Desktop.
Save rhernandog/6d1a14e647d8a8083503d1d2274d671a to your computer and use it in GitHub Desktop.
Suggestion of a class that returns a PIXI Sprite object with a simple configuration.
/* CREATE PIXI SPRITE CLASS
* In order to clean the code create a class that returns the sprite
* for the background image.
* Most common cases for sprites are position, scale, width, height,
* anchor and alpha;
* @param {string} the image url
* @param {object} configurations of the sprite
*/
var createPixiSprite = function(imgURL, config){
var pixiSprite = PIXI.Sprite.fromImage(imgURL);
for( var key in config ) {
// in the case of x and y properties, remove the final letter
// and set the properties in the PIXI way property.x
if( key.slice(-1) === "X" || key.slice(-1) === "Y") {
// assign the value to the property
pixiSprite[key.slice(0,-1)][key.slice(-1).toLowerCase()] = config[key];
} else {
// if no letter is passed, means a property that has only one option
// or a general value for the x and y options.
// for scale, anchor and position use the same value for both
switch (key) {
case "scale":
pixiSprite.scale.x = config[key];
pixiSprite.scale.y = config[key];
break;
case "position":
pixiSprite.position.x = config[key];
pixiSprite.position.y = config[key];
break;
case "anchor":
pixiSprite.anchor.x = config[key];
pixiSprite.anchor.y = config[key];
break;
default:
pixiSprite[key] = config[key];
}// switch end
}// conditional end
}// loop end
return pixiSprite;
};
// usage
var image = new createPixiSprite('pngs/landscape.jpg', {
scale: 0.45, anchor: 0.5, positionX : 102.5, positionY : 127.5, alpha: 0
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment