How to scale and center Pixi.js stage?
How to scale and center Pixi.js stage?
by Alexander Farber
HTML
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pixi.min.js"></script>
<div id="mainDiv">
<div id="leftMenuDiv">
<button id="btn1">Button 1</button><br>
<button id="btn2">Button 2</button><br>
<button id="btn3">Button 3</button><br>
</div>
<div id="canvasDiv">
<canvas id="pixiCanvas"></canvas>
</div>
<div id="rightMenuDiv">
<input id="scaleCheck" type="checkbox">
<label for="scaleCheck">Scale and center Pixi stage</label><br>
<button id="btn4">Button 4</button><br>
<button id="btn5">Button 5</button><br>
<button id="btn6">Button 6</button><br>
</div>
</div>
CSS
body {
margin: 0;
padding: 0;
}
#mainDiv {
width: 100%;
height: 100vh;
background: #FFF;
display: flex;
}
#leftMenuDiv {
text-align: center;
background: #FCC;
}
#rightMenuDiv {
text-align: center;
background: #CFC;
flex-shrink: 1;
}
#canvasDiv {
flex-grow: 1;
}
#pixiCanvas {
width: 100%;
height: 100%;
background: #CCF;
box-sizing: border-box;
border: 4px red dotted;
}
JavaScript
$(function() {
var WIDTH = 400;
var HEIGHT = 400;
var RATIO = WIDTH / HEIGHT;
var scaleX = 1,
scaleY = 1,
offsetX = 0,
offsetY = 0,
oldX, oldY;
var app = new PIXI.Application({
width: WIDTH,
height: HEIGHT,
view: document.getElementById('pixiCanvas'),
backgroundColor: 0xFFFFFF
});
app.stage.interactive = true;
app.stage.on('pointerdown', onDragStart)
.on('pointerup', onDragEnd)
.on('pointerupoutside', onDragEnd)
.on('pointermove', onDragMove);
var background = new PIXI.Graphics();
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
if ((i + j) % 2 == 0) {
background.beginFill(0xCCCCFF);
background.drawRect(i * WIDTH / 8, j * HEIGHT / 8, WIDTH / 8, HEIGHT / 8);
background.endFill();
}
}
}
app.stage.addChild(background);
var bunny = PIXI.Sprite.from('https://pixijs.io/examples/examples/assets/bunny.png');
bunny.anchor.set(0.5);
bunny.scale.set(2);
bunny.x = WIDTH / 2;
bunny.y = HEIGHT / 2;
app.stage.addChild(bunny);
function onDragStart(ev) {
var stagePoint = ev.data.getLocalPosition(app.stage);
if (bunny.getBounds().contains(stagePoint.x, stagePoint.y)) {
bunny.alpha = 0.5;
oldX = stagePoint.x;
oldY = stagePoint.y;
this.data = ev.data;
}
}
function onDragMove() {
if (this.data) {
var stagePoint = this.data.getLocalPosition(app.stage);
bunny.x += stagePoint.x - oldX;
bunny.y += stagePoint.y - oldY;
oldX = stagePoint.x;
oldY = stagePoint.y;
}
}
function onDragEnd() {
if (this.data) {
bunny.alpha = 1;
var stagePoint = this.data.getLocalPosition(app.stage);
this.data = null;
}
}
...