Skip to content

Instantly share code, notes, and snippets.

@ariel-frischer
Forked from only-cliches/pixibackground.js
Last active July 17, 2020 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ariel-frischer/def13355c2ed601d54b3faeddbef5187 to your computer and use it in GitHub Desktop.
Save ariel-frischer/def13355c2ed601d54b3faeddbef5187 to your computer and use it in GitHub Desktop.
PixiJS Background Cover & Background Container Typescript
export enum PIXI_CONTAINER_TYPE {
COVER,
CONTAIN,
}
export function getPixiContainer(bgSize: PIXI.Point, inputSprite: PIXI.Sprite, type: PIXI_CONTAINER_TYPE, forceSize?: PIXI.Point) {
let sprite = inputSprite;
let bgContainer = new PIXI.Container();
let mask = new PIXI.Graphics().beginFill(0x8bc5ff).drawRect(0, 0, bgSize.x, bgSize.y).endFill();
bgContainer.mask = mask;
bgContainer.addChild(mask);
bgContainer.addChild(sprite);
function resize() {
let spriteSize = new PIXI.Point(sprite.width, sprite.height);
if (forceSize) spriteSize = forceSize;
let winratio = bgSize.x / bgSize.y;
let spratio = spriteSize.x / spriteSize.y;
let scale = 1;
let pos = new PIXI.Point(0, 0);
if (type === PIXI_CONTAINER_TYPE.COVER ? winratio > spratio : winratio < spratio) {
//photo is wider than background
scale = bgSize.x / spriteSize.x;
pos.y = -(spriteSize.y * scale - bgSize.y) / 2;
} else {
//photo is taller than background
scale = bgSize.y / spriteSize.y;
pos.x = -(spriteSize.x * scale - bgSize.x) / 2;
}
sprite.scale = new PIXI.Point(scale, scale);
sprite.position = pos;
}
resize();
return {
container: bgContainer,
doResize: resize,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment