Pixi cache animation

by bones

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/3.0.8/pixi.min.js"></script>
<canvas id="natCanvas" width=350 height=250 ></canvas>
<canvas id="pixiCanvas" width=350 height=250 ></canvas>

CSS

canvas {
  width: 350px;
  height: 250px;
  background-color: #333;
}

JavaScript

var circle = [
  [
    [50, 70],
    [50, 42.386],
    [72.386, 20],
    [100, 20]
  ],
  [
    [100, 20],
    [127.614, 20],
    [150, 42.386],
    [150, 70]
  ],
  [
    [150, 70],
    [150, 97.614],
    [127.614, 120],
    [100, 120]
  ],
  [
    [100, 120],
    [72.386, 120],
    [50, 97.614],
    [50, 70]
  ]
];

var square = [
  [
    [50, 200],
    [50, 200],
    [50, 50],
    [50, 50]
  ],
  [
    [50, 50],
    [50, 50],
    [200, 50],
    [200, 50]
  ],
  [
    [200, 50],
    [200, 50],
    [200, 200],
    [200, 200]
  ],
  [
    [200, 200],
    [200, 200],
    [50, 200],
    [50, 200]
  ]
];

var natCanvas = document.getElementById('natCanvas');
var ctx = natCanvas.getContext('2d');
var f = 0;
var speed = 0.05; //20 frame animation
var direction = 1;

// === GAME LOOP =====
function loop() {
  nativeCanvasLoop();
  pixiLoop();
  requestAnimationFrame(loop);
}


function nativeCanvasLoop(){
  var path = interpolatePath(circle, square, f);
  nativeDraw(path);
  f += speed * direction;
  f = Math.round(f*100)/100;
  //loop back
  if (f > 1) { f=1; direction = -1; }
  if (f < 0) { f=0; direction = 1; }    
}

// ==== PATH INTERPOLATION ====
var path = [], point;
function interpolatePath(path1, path2, f) {
  if (f ===0) return path1;
  if (f ===1) return path2; 
  path = [];
  
  for (var i = 0; i < path1.length; i++) {
    curveA = path1[i];
    curveB = path2[i];
    path[i] = [
      interpolatePoint(curveA[0], curveB[0], f),
      interpolatePoint(curveA[1], curveB[1], f),
      interpolatePoint(curveA[2], curveB[2], f),
      interpolatePoint(curveA[3], curveB[3], f)
    ];
  }
  return path;
}
function interpolatePoint(p1, p2, f){
   if (!p1 || !p2) return;
   return [ 
     (p1[0] + (p2[0] - p1[0])*f),
     (p1[1] + (p2[1] - p1[1])*f)
   ];
}

// === PATH DRAWING =====
function nativeDraw(path) {
  ctx.clearRect(0, 0, 800, 400);
  ctx.beginPath();
  ctx.lineWidth = 2;
  ctx.strokeStyle = "#ffffff";
  drawPath(path, ctx);
  ctx.stroke();
}

//draw to...