Projecting 3D object on 2D plane using pixiJS


Perspective projection activity came up in Introduction to computer graphics course.

Sample implementation using PixiJS, and this is what it looks like.

sampleimage

<html>
  <head>
    <script src="https://pixijs.download/release/pixi.js"></script>
    <script type="module">
      const app = new PIXI.Application();
      await app.init({ width: 640, height: 360 });
      document.body.appendChild(app.canvas);
      var cubeVertices = [
        [1, 1, 1],
        [1, 1, -1],
        [1, -1, 1],
        [1, -1, -1],
        [-1, 1, 1],
        [-1, 1, -1],
        [-1, -1, 1],
        [-1, -1, -1],
      ];
      var cameraPostition = [2, 3, 5];
      var projectedVertices = [];
      cubeVertices.forEach((pos) => {
        var cameraShift = [
          pos[0] - cameraPostition[0],
          pos[1] - cameraPostition[1],
          pos[2] - cameraPostition[2],
        ];

        projectedVertices.push([
          cameraShift[0] / cameraShift[2],
          cameraShift[1] / cameraShift[2],
        ]);
      });
      var scale = 200;
      projectedVertices.forEach((pos) => {
        let obj = new PIXI.Graphics()
          .circle(pos[0] * scale, pos[1] * scale, 5)
          .fill("red");
        app.stage.addChild(obj);
      });
    </script>
  </head>
  <body></body>
</html>