Last active
April 5, 2023 07:54
-
-
Save thibka/4f526e08d12a8b0bb3d8fd468e24ab17 to your computer and use it in GitHub Desktop.
PixiJS - Set sprite size to cover/contain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Example: