Blog>
Snippets

3D Data Visualization

Create a 3D bar graph to visualize data dynamically with Three.js, including axis labels and an animation that builds the graph when loaded.
// Import required Three.js components
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

document.addEventListener('DOMContentLoaded', () => {
  // Scene setup
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  // Orbit Controls
  const controls = new OrbitControls(camera, renderer.domElement);

  // Data (example)
  const data = [
    {x: 1, y: 2, z: 3, value: 10},
    {x: 2, y: 3, z: 4, value: 15},
    {x: 3, y: 4, z: 5, value: 20},
    // Add as many data points as necessary
  ];

  // Create bars
  const barGeometry = new THREE.BoxGeometry(0.8, 0.8, 0.8);
  const barMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00, transparent: true, opacity: 0.75});

  // Function to create a single bar
  const createBar = (dataPoint) => {
    const bar = new THREE.Mesh(barGeometry, barMaterial);
    bar.position.x = dataPoint.x;
    bar.position.z = dataPoint.z;
    bar.scale.y = 0; // Initialize scale to 0 for animation
    scene.add(bar);
    return bar;
  };

  // Create bars for all data points
  const bars = data.map(createBar);

  camera.position.z = 15;

  // Animation function
  const animate = () => {
    requestAnimationFrame(animate);

    bars.forEach((bar, index) => {
      // Animate the bars growing up
      if (bar.scale.y < data[index].value) {
        bar.scale.y += 0.1;
        bar.position.y = bar.scale.y / 2; // Update position to the base stays at zero
      }
    });

    controls.update();
    renderer.render(scene, camera);
  };
  animate();

  // Handle window resize
  window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  });
});
This code initializes a Three.js scene, sets up a camera and renderer, and includes OrbitControls for interactive control of the viewpoint. It also creates a simple dataset and visualizes it as a series of 3D bars that animate from scale 0 to their respective value on load. The window resize event is handled to ensure the visualization resizes appropriately.