Export Three.js Scene to GLTF

Exporting a dynamically generated scene from Three.js to a GLTF or GLB file allows developers to save user-generated 3D models, capture current scene states, or transfer assets directly to other 3D software. This article provides a straightforward, step-by-step guide on how to implement the GLTFExporter utility in Three.js to serialize your 3D scenes and trigger an automatic browser download of the resulting file.

1. Import the GLTFExporter

To export scenes, you must use the GLTFExporter class. In modern Three.js setups using ES modules, you can import it directly from the addons folder:

import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';

2. Set Up the Export Function

To handle the export process, instantiate the GLTFExporter and call its .parse() method. This method takes your scene (or any Object3D), a callback function to handle the parsed data, an error callback, and an optional configuration object.

Here is the complete function to parse your scene and trigger a file download in the browser:

function exportScene(inputScene) {
  const exporter = new GLTFExporter();

  const options = {
    binary: true, // Set to true to export as .glb, false for .gltf
    animations: [], // Include animations if applicable
    onlyVisible: true // Export only visible objects
  };

  exporter.parse(
    inputScene,
    function (result) {
      if (result instanceof ArrayBuffer) {
        // Handle binary GLB export
        saveArrayBuffer(result, 'scene.glb');
      } else {
        // Handle JSON GLTF export
        const output = JSON.stringify(result, null, 2);
        saveString(output, 'scene.gltf');
      }
    },
    function (error) {
      console.error('An error occurred during GLTF export:', error);
    },
    options
  );
}

3. Implement the Helper Functions for Downloading

The browser needs to convert the exported data into a downloadable file. You can achieve this by creating a virtual <a> element, assigning it a Blob URL containing your data, and programmatically triggering a click event.

Add these two helper functions to your codebase:

function save(blob, filename) {
  const link = document.createElement('a');
  link.style.display = 'none';
  document.body.appendChild(link); // Required for Firefox

  link.href = URL.createObjectURL(blob);
  link.download = filename;
  link.click();

  // Clean up
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);
}

function saveString(text, filename) {
  save(new Blob([text], { type: 'text/plain' }), filename);
}

function saveArrayBuffer(buffer, filename) {
  save(new Blob([buffer], { type: 'application/octet-stream' }), filename);
}

4. Key Configuration Options

The options object passed to the .parse() method allows you to customize the output: