Skip to content

Instantly share code, notes, and snippets.

@thibka
Last active April 5, 2023 07:54
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thibka/4f526e08d12a8b0bb3d8fd468e24ab17 to your computer and use it in GitHub Desktop.
Save thibka/4f526e08d12a8b0bb3d8fd468e24ab17 to your computer and use it in GitHub Desktop.
PixiJS - Set sprite size to cover/contain
/*
WIP
Only works for full screen sprites.
width: width of the sprite container
height: height of the sprite container
type: "cover" or "contain"
*/
PIXI.Sprite.prototype.setSize = function(width, height, type) {
var texture = { width: this.texture.width, height: this.texture.height },
targetRatio = width / height,
textureRatio = this.texture.width / this.texture.height,
scale,
pos = new PIXI.Point(0, 0);
if (type == 'cover') {
if (targetRatio > textureRatio) {
scale = width / texture.width;
pos.y = -((texture.height * scale) - height) / 2
} else {
scale = height / texture.height;
pos.x = -((texture.width * scale) - width) / 2
}
} else {
if (targetRatio > textureRatio) {
scale = height / texture.height;
pos.x = -((texture.width * scale) - width) / 2
}
else {
scale = width / texture.width;
pos.y = -((texture.height * scale) - height) / 2
}
}
this.scale.set(scale);
this.position = pos;
}
@thibka
Copy link
Author

thibka commented Aug 28, 2019

Usage:

sprite.setSize(width, height, "cover");

Example:

function setSpriteSize() {
    sprite.setSize(app.renderer.width, app.renderer.height, "cover");
}

window.addEventListener('resize', setSpriteSize);
setSpriteSize();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment