JSFiddle - React, Tailwind, and code Playground

by tfoller

HTML

<canvas id="main_canvas" width="550" height="550"></canvas>
   
 <script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
  <script type="importmap">
    {
      "imports": {
        "three": "https://unpkg.com/three@0.145.0/build/three.module.js",
        "three/addons/": "https://unpkg.com/three@0.145.0/examples/jsm/"
      }
    }
  </script>

CSS

body {
  background-color: #020408;
  color: #ccc;
}

JavaScript

import * as THREE from 'three'

import { makeCube } from 'https://alikim.com/jsm/test/makeCube.js'

// 3D

const canvas = document.getElementById('main_canvas');
const [w, h] = [canvas.width, canvas.height];
const renderer = new THREE.WebGLRenderer({
  antialias: true,
  canvas: canvas,
});
renderer.setSize(w, h);

const [near, far] = [1, 700];
const mid = -0.5 * (near + far);
const camera = new THREE.PerspectiveCamera(45, w / h, near, far);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0, 0, 0.3);

const dirLight = new THREE.DirectionalLight(0xffffff, 0.5);
dirLight.position.set(1, 1, 1);
scene.add(dirLight);

const size = 100;
const cube = makeCube(size); console.log(cube);

cube.position.z = mid;
scene.add(cube);

const hlp = new THREE.AxesHelper(110);
hlp.position.z = mid;
scene.add(hlp);

const anim = () => {
  cube.rotation.x += 0.013;
  cube.rotation.y += 0.007;
};

const framerate = 60;
const fpsint = 1000 / framerate;
let elapsed, now, then;

const state = { 
  play: true, 
  flip: function() { 
    this.play = !this.play;
    renderFrame();
  } 
};

function render() { renderer.render(scene, camera) }

function maybeRender() { if (!state.play) render() }

const renderFrame = newtime => {
  if (!state.play) return;
  requestAnimationFrame(renderFrame);
  if (!newtime) then = newtime = window.performance.now();
  now = newtime;
  elapsed = now - then;
  if (!fpsint || elapsed > fpsint) {
    then = now - (elapsed % fpsint);

    render();
    anim();
  }
};

renderFrame();