JSFiddle - React, Tailwind, and code Playground

by Johan Vandeplas

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Three.js Web Component Example</title>
  <style>
    body { margin: 0; }
    three-container { display: block; width: 100%; height: 100vh; }
  </style>
</head>
<body>
  <!-- Use the custom web component -->
  <three-container></three-container>

  <script type="module">
    import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';

    class ThreeContainer extends HTMLElement {
      constructor() {
        super();
        this.attachShadow({ mode: 'open' });
      }

      connectedCallback() {
        this.initThreeJS();
      }

      initThreeJS() {
        const width = this.clientWidth;
        const height = this.clientHeight;

        // Create scene
        const scene = new THREE.Scene();

        // Create camera
        const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
        camera.position.z = 5;

        // Create renderer
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(width, height);
        this.shadowRoot.appendChild(renderer.domElement);

        // Add a light
        const light = new THREE.AmbientLight(0x404040);
        scene.add(light);

        // Example container dimensions and box data
        const container = { width: 2, height: 2, depth: 2 };
        const boxes = [
          { width: 1, height: 1, depth: 1, position: { x: -0.5, y: -0.5, z: -0.5 } },
          { width: 0.5, height: 0.5, depth: 0.5, position: { x: 1, y: 0.5, z: 0.5 } }
        ];

        // Create container (a wireframe box)
        const containerGeometry = new THREE.BoxGeometry(container.width, container.height, container.depth);
        const containerMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true });
        const containerMesh = new THREE.Mesh(containerGeometry, containerMaterial);
       ...