-
-
Save ariel-frischer/def13355c2ed601d54b3faeddbef5187 to your computer and use it in GitHub Desktop.
PixiJS Background Cover & Background Container Typescript
This file contains 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
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