PIXI Canvas Zoom

A Pixi Canvas which can zoom in on an element to the point it takes the whole container's size

by Muhammad Adnan

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.6.2/pixi.js"></script>

JavaScript

var display = document.createElement("div");
display.setAttribute("id", "display");

var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, {
            transparent: true,
            anitalias: true
        });
        
document.getElementsByTagName('body')[0].appendChild(renderer.view);
renderer.view.style.border = "1px dashed black";

var stage = new PIXI.Container();

//Creating the element to zoom
graphics = new PIXI.Graphics();
graphics.beginFill(0x2F7455);
graphics.drawRect(100, 100, 75, 50);
graphics.endFill();
graphics.interactive = true;

//next time set position, not the rect offset.
//graphics.position.set(100, 100);


graphics.click = function (){
  grow();
  console.log("I WAS CLICKED");
}

stage.addChild(graphics);

function animate() {
	requestAnimationFrame(animate);
  renderer.render(stage);
}

function grow() {
	requestAnimationFrame(grow);
	//lets take original graphics size
  //lets take original graphics size
  var oldSize = graphics.getLocalBounds();
  var scaleGoalX = renderer.screen.width / oldSize.width;
  var scaleGoalY = renderer.screen.width / oldSize.height;
  var pivotGoalX = oldSize.x;
  var pivotGoalY = oldSize.y;

  //adjust lets see
  if (stage.scale.x < scaleGoalX) {
    stage.scale.x += 0.5;
  }
  if (stage.scale.y < scaleGoalY) {
    stage.scale.y += 0.5;
  }

  if (stage.pivot.x < pivotGoalX) {
    stage.pivot.x += 2;
  }
  if (stage.pivot.y < pivotGoalY) {
    stage.pivot.y += 2;
  }
}

animate();