Skip to content

Instantly share code, notes, and snippets.

@duskvirkus
Created November 18, 2019 06:44
Show Gist options
  • Save duskvirkus/b1d8da362a6597dded4e805a1dabdaff to your computer and use it in GitHub Desktop.
Save duskvirkus/b1d8da362a6597dded4e805a1dabdaff to your computer and use it in GitHub Desktop.
simple pixi js sketch which adapts to the browser window's size
import * as PIXI from 'pixi.js';
import { setupSize, windowWidth, windowHeight } from './src/size';
import floppyImage from './assets/floppy.png';
// Globals
let app;
let canvas;
const canvasID = 'app-canvas';
let container;
let floppyTexture;
// Init
if (document.readyState === 'complete') {
init();
} else {
window.addEventListener('load', init, false);
}
function resized() {
canvas.width = windowWidth;
canvas.height = windowHeight;
app.renderer.resize(canvas.width, canvas.height);
positionContainer();
}
function init() {
canvas = document.getElementById(canvasID);
app = new PIXI.Application({
backgroundColor: 0xffffff,
resolution: window.devicePixelRatio || 1,
view: canvas,
forceCanvas: false,
});
container = new PIXI.Container();
app.stage.addChild(container);
floppyTexture = PIXI.Texture.from(floppyImage);
const floppy = new PIXI.Sprite(floppyTexture);
floppy.anchor.set(0.5);
container.addChild(floppy);
container.pivot.x = container.width / 2;
container.pivot.y = container.height / 2;
setupSize(resized);
app.ticker.add(loop);
}
// Loop
function loop(delta) {
container.rotation -= 0.01 * delta;
}
// Other
function positionContainer() {
container.x = app.screen.width / 2;
container.y = app.screen.height / 2;
}
export let windowWidth;
export let windowHeight;
let _callback = null;
export const getWindowWidth = () => {
return (
window.innerWidth ||
(document.documentElement && document.documentElement.clientWidth) ||
(document.body && document.body.clientWidth) ||
0
);
};
export const getWindowHeight = () => {
return (
window.innerHeight ||
(document.documentElement && document.documentElement.clientHeight) ||
(document.body && document.body.clientHeight) ||
0
);
};
export const windowResized = () => {
windowWidth = getWindowWidth();
windowHeight = getWindowHeight();
if (_callback) {
_callback();
}
};
export const setupSize = (callback) => {
if (callback) {
setSizeCallback(callback);
}
window.addEventListener('resize', windowResized);
windowResized();
};
export const setSizeCallback = (callback) => {
_callback = callback;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment