JSFiddle - React, Tailwind, and code Playground

by farazshaikh

HTML

<script src="https://cdn.jsdelivr.net/gh/matthiasferch/tsm/dist/tsm.js"></script>
<script src="https://cdn.jsdelivr.net/gh/WesUnwin/obj-file-parser/src/OBJFile.js"></script>
<canvas width="600px" height="600px"></canvas>

CSS

body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

JavaScript

window.onload = function() {

  const canvas = document.querySelector("canvas");
  const ctx = canvas.getContext("2d");

  const TSM = tsm.default

  class Triangle {
    constructor(verts) {
      this.verts = verts
    }
  }


  class Mesh {
    constructor() {
      this.tris = [];
    }

    load(src, callback) {
      fetch(src)
        .then((res) => res.text())
        .then((data) => {
          const d = new OBJFile(data, "cube").parse()
          d.models.forEach(({
            faces,
            vertices
          }) => {
            faces.forEach((f) => {
              const verts = f.vertices.map((v) => {
                const i = v.vertexIndex - 1;
                return new TSM.vec3([vertices[i].x, vertices[i].y, vertices[i].z]);
              });

              this.tris.push(new Triangle(verts));
            });
          });
          callback()
        })
        .catch(console.error);
    }
  }



  const cube = new Mesh()
  cube.load('https://gist.githubusercontent.com/MaikKlein/0b6d6bb58772c13593d0a0add6004c1c/raw/48cf9c6d1cdd43cc6862d7d34a68114e2b93d497/cube.obj', main.bind(this))

  const camera = new TSM.vec3([0, 0, 0]);

  const near = 0;
  const far = 1000;
  const fov = 90;
  const aspectRatio = canvas.height / canvas.width;
  const fovRad = 1 / Math.tan(((fov * 0.5) / 180) * Math.PI);
  

  const projectionMatrix = (function() {
    const mat = new TSM.mat4(new Array(16).fill(0));
    mat.values[(4 * 0) + 0] = aspectRatio * fovRad
    mat.values[(4 * 1) + 1] = fovRad
    mat.values[(4 * 2) + 2] = -(far  / (far - near));
    mat.values[(4 * 3) + 2] = -((far * near) / (far - near));
    mat.values[(4 * 2) + 3] = -1;
    mat.values[(4 * 3) + 3] = 0;
    return mat;
  })();

	const rotateX = function (theta) {
	  const mat = new TSM.mat4(new Array(16).fill(0));
	  mat.values[4 * 0 + 0] = 1;
	  mat.values[4 * 1 + 1] = Math.cos(theta);
	  mat.values[4 * 1 + 2] = Math.sin(theta);
	  mat.values[4 * 2 + 1] = -Math.sin(theta);
	  mat.values[4 *...