TechSetupGuides
Intermediatesveltethreejs3dwebglgraphicsfrontendtypescriptanimationvrar

Threlte - 3D Framework for Svelte

A declarative, type-safe, and reactive 3D framework for building interactive web applications using Svelte and Three.js.

  1. Step 1

    Overview

    Threlte is a Svelte library for creating interactive 3D web applications powered by Three.js. It provides a declarative, type-safe, reactive, and interactive API that lets you build 3D scenes using Svelte's component patterns instead of imperative Three.js code. With built-in support for physics (Rapier), animation (Theatre.js), and VR/AR experiences, Threlte makes 3D web development more accessible to Svelte developers.

  2. Step 2

    Technology Stack

    Threlte is built on top of modern web technologies and provides a comprehensive ecosystem for 3D development.

    Language: TypeScript / JavaScript
    Framework: Svelte / SvelteKit
    3D Engine: Three.js
    License: MIT
    Stars: 3.3K+
    Owner: threlte
    Repo: https://github.com/threlte/threlte
    Docs: https://threlte.xyz
    
    Core Packages:
    - @threlte/core - Three.js bindings for Svelte
    - @threlte/extras - Extended components and helpers
    - @threlte/gltf - CLI for converting GLTF assets to components
    - @threlte/rapier - Physics engine integration
    - @threlte/theatre - Animation studio support
    - @threlte/xr - VR and AR components
    - @threlte/flex - Layout engine for 3D UIs
    - @threlte/studio - Spatial programming tools
  3. Step 3

    Prerequisites

    Before installing Threlte, ensure you have a Svelte or SvelteKit project set up. If you're starting from scratch, create a new SvelteKit project first.

    # Create a new SvelteKit project (if needed)
    npm create svelte@latest my-threlte-app
    cd my-threlte-app
    npm install
  4. Step 4

    Quick Start with CLI

    The easiest way to get started with Threlte is using the interactive CLI scaffolding tool. This creates a new SvelteKit project and automatically installs and configures Threlte and its dependencies.

    # Scaffold a new Threlte project
    npm create threlte
    
    # Follow the interactive prompts to:
    # 1. Choose your project name
    # 2. Select which Threlte packages to install
    # 3. Configure your setup
  5. Step 5

    Manual Installation

    For existing projects, install Threlte packages manually. The minimum requirement is three and @threlte/core. Additional packages can be added anytime.

    # Minimum installation
    npm install three @threlte/core
    
    # TypeScript support (recommended)
    npm install -D @types/three
    
    # Optional packages for extended functionality
    npm install @threlte/extras
    npm install @threlte/rapier
    npm install @threlte/theatre
    npm install @threlte/xr
    npm install @threlte/flex
  6. Step 6

    Basic Scene Setup

    Create your first 3D scene with Threlte. The Canvas component is the root that creates a renderer, default camera, and provides the Threlte runtime context.

    <!-- App.svelte -->
    <script>
      import { Canvas } from '@threlte/core'
      import Scene from './Scene.svelte'
    </script>
    
    <Canvas>
      <Scene />
    </Canvas>
    
    <style>
      :global(body) {
        margin: 0;
        padding: 0;
      }
    </style>
  7. Step 7

    Creating a 3D Cube

    Build your first 3D object using the T component, which is the main building block of Threlte applications. The T component creates Three.js objects declaratively.

    <!-- Scene.svelte -->
    <script>
      import { T } from '@threlte/core'
    </script>
    
    <!-- Basic cube with default material -->
    <T.Mesh>
      <T.BoxGeometry />
      <T.MeshBasicMaterial color="hotpink" />
    </T.Mesh>
  8. Step 8

    Adding Camera and Lighting

    Enhance your scene with a custom camera position and lighting. Use MeshStandardMaterial for realistic lighting effects.

    <!-- Scene.svelte -->
    <script>
      import { T } from '@threlte/core'
    </script>
    
    <!-- Custom camera -->
    <T.PerspectiveCamera
      makeDefault
      position={[10, 10, 10]}
      oncreate={(ref) => {
        ref.lookAt(0, 1, 0)
      }}
    />
    
    <!-- Directional light with shadows -->
    <T.DirectionalLight position={[0, 10, 10]} castShadow />
    
    <!-- Cube with standard material -->
    <T.Mesh position.y={1} castShadow>
      <T.BoxGeometry args={[1, 2, 1]} />
      <T.MeshStandardMaterial color="hotpink" />
    </T.Mesh>
    
    <!-- Ground plane -->
    <T.Mesh rotation.x={-Math.PI / 2} receiveShadow>
      <T.CircleGeometry args={[4, 40]} />
      <T.MeshStandardMaterial color="white" />
    </T.Mesh>
  9. Step 9

    Animation with useTask

    Add continuous animation using the useTask hook, which runs on every frame. This is perfect for rotating objects or updating positions over time.

    <!-- Scene.svelte -->
    <script>
      import { T, useTask } from '@threlte/core'
      
      let rotation = $state(0)
      
      // Run on every frame
      useTask((delta) => {
        rotation += delta
      })
    </script>
    
    <T.Mesh rotation.y={rotation}>
      <T.BoxGeometry />
      <T.MeshStandardMaterial color="hotpink" />
    </T.Mesh>
  10. Step 10

    Adding Interactivity

    Make your 3D objects interactive with pointer events. The interactivity plugin from @threlte/extras enables event listeners like pointerenter, pointerleave, and onclick.

    <!-- Scene.svelte -->
    <script>
      import { T, useTask } from '@threlte/core'
      import { interactivity } from '@threlte/extras'
      import { Spring } from 'svelte/motion'
      
      // Enable interactivity plugin
      interactivity()
      
      const scale = new Spring(1)
      let rotation = $state(0)
      
      useTask((delta) => {
        rotation += delta
      })
    </script>
    
    <T.Mesh
      rotation.y={rotation}
      scale={scale.current}
      onpointerenter={() => { scale.target = 1.5 }}
      onpointerleave={() => { scale.target = 1 }}
    >
      <T.BoxGeometry />
      <T.MeshStandardMaterial color="hotpink" />
    </T.Mesh>
  11. Step 11

    Complete Interactive Scene Example

    Full example combining camera, lighting, animation, and interactivity with shadows and smooth animations.

    <!-- Scene.svelte -->
    <script>
      import { T, useTask } from '@threlte/core'
      import { interactivity } from '@threlte/extras'
      import { Spring } from 'svelte/motion'
      
      interactivity()
      const scale = new Spring(1)
      let rotation = $state(0)
      
      useTask((delta) => {
        rotation += delta
      })
    </script>
    
    <T.PerspectiveCamera
      makeDefault
      position={[10, 10, 10]}
      oncreate={(ref) => {
        ref.lookAt(0, 1, 0)
      }}
    />
    
    <T.DirectionalLight position={[0, 10, 10]} castShadow />
    
    <T.Mesh
      rotation.y={rotation}
      position.y={1}
      scale={scale.current}
      castShadow
      onpointerenter={() => { scale.target = 1.5 }}
      onpointerleave={() => { scale.target = 1 }}
    >
      <T.BoxGeometry args={[1, 2, 1]} />
      <T.MeshStandardMaterial color="hotpink" />
    </T.Mesh>
    
    <T.Mesh rotation.x={-Math.PI / 2} receiveShadow>
      <T.CircleGeometry args={[4, 40]} />
      <T.MeshStandardMaterial color="white" />
    </T.Mesh>
  12. Step 12

    Loading 3D Models (GLTF)

    Import and display 3D models using the @threlte/extras GLTF loader or convert models to Threlte components with the @threlte/gltf CLI.

    # Convert GLTF to Threlte component
    npx @threlte/gltf model.gltf
    
    # This creates a reusable Svelte component from your 3D model
  13. Step 13

    Using GLTF Components

    After converting a GLTF model with the CLI, use it like any other Svelte component.

    <!-- Scene.svelte -->
    <script>
      import { T } from '@threlte/core'
      import Model from './Model.svelte'  // Generated by @threlte/gltf
    </script>
    
    <T.PerspectiveCamera makeDefault position={[0, 5, 10]} />
    <T.DirectionalLight position={[5, 5, 5]} />
    
    <Model scale={2} position={[0, 0, 0]} />
  14. Step 14

    Physics with Rapier

    Add realistic physics simulation to your 3D scenes using the @threlte/rapier package. This example shows how to create falling rigid bodies.

    <!-- Scene.svelte -->
    <script>
      import { T } from '@threlte/core'
      import { World, RigidBody, AutoColliders } from '@threlte/rapier'
    </script>
    
    <World gravity={[0, -9.81, 0]}>
      <!-- Ground -->
      <RigidBody type="fixed">
        <AutoColliders shape="cuboid">
          <T.Mesh position.y={-0.5}>
            <T.BoxGeometry args={[10, 1, 10]} />
            <T.MeshStandardMaterial color="gray" />
          </T.Mesh>
        </AutoColliders>
      </RigidBody>
      
      <!-- Falling cube -->
      <RigidBody>
        <AutoColliders shape="cuboid">
          <T.Mesh position.y={5}>
            <T.BoxGeometry />
            <T.MeshStandardMaterial color="hotpink" />
          </T.Mesh>
        </AutoColliders>
      </RigidBody>
    </World>
  15. Step 15

    VR/AR Support

    Build immersive VR and AR experiences using the @threlte/xr package. This enables WebXR functionality with minimal setup.

    <!-- App.svelte -->
    <script>
      import { Canvas } from '@threlte/core'
      import { XR, Hand, Controller } from '@threlte/xr'
      import Scene from './Scene.svelte'
    </script>
    
    <Canvas>
      <XR>
        <Hand hand="left" />
        <Hand hand="right" />
        <Controller left />
        <Controller right />
        <Scene />
      </XR>
    </Canvas>
  16. Step 16

    Common Use Cases

    Threlte excels at various 3D web application scenarios.

    1. Interactive Product Showcases
       - 3D product configurators
       - Virtual showrooms
       - E-commerce visualizations
    
    2. Data Visualization
       - 3D charts and graphs
       - Spatial data representation
       - Interactive dashboards
    
    3. Games and Experiences
       - Browser-based games
       - Interactive storytelling
       - Educational simulations
    
    4. VR/AR Applications
       - Virtual tours
       - Immersive training
       - Collaborative 3D spaces
    
    5. Creative Portfolios
       - Animated landing pages
       - Interactive art installations
       - 3D typography and effects
  17. Step 17

    Performance Optimization

    Tips for optimizing Threlte applications for better performance and smaller bundle sizes.

    // vite.config.js - Optimize Three.js bundle
    export default {
      ssr: {
        noExternal: ['three', 'troika-three-text']
      },
      optimizeDeps: {
        include: ['three']
      }
    }
    
    // Use level of detail (LOD)
    import { T } from '@threlte/core'
    import { LOD } from 'three'
    
    // Dispose of unused resources
    import { onDestroy } from 'svelte'
    import { useThrelte } from '@threlte/core'
    
    const { scene } = useThrelte()
    onDestroy(() => {
      scene.traverse((object) => {
        if (object.geometry) object.geometry.dispose()
        if (object.material) object.material.dispose()
      })
    })
  18. Step 18

    SvelteKit Integration

    Configure Threlte for optimal performance in SvelteKit projects, including SSR handling.

    <!-- +page.svelte -->
    <script>
      import { browser } from '$app/environment'
      import { Canvas } from '@threlte/core'
      import Scene from './Scene.svelte'
    </script>
    
    {#if browser}
      <Canvas>
        <Scene />
      </Canvas>
    {:else}
      <div class="loading">Loading 3D scene...</div>
    {/if}
    
    <style>
      .loading {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
      }
    </style>
  19. Step 19

    Debugging and Development

    Useful tools and techniques for debugging Threlte applications.

    <!-- Scene.svelte -->
    <script>
      import { T, useThrelte } from '@threlte/core'
      import { OrbitControls } from '@threlte/extras'
      
      // Access Three.js internals for debugging
      const { renderer, scene, camera } = useThrelte()
      
      // Log scene graph
      $: console.log('Scene:', $scene)
    </script>
    
    <!-- Add orbit controls for easy navigation during development -->
    <OrbitControls />
    
    <!-- Enable stats display -->
    <T.PerspectiveCamera makeDefault position={[5, 5, 5]} />
    
    <!-- Your scene objects here -->
  20. Step 20

    Key Features Summary

    Overview of Threlte's core capabilities and advantages.

    ✓ Declarative Three.js - Build 3D scenes with Svelte components
    ✓ Fully Reactive - Leverage Svelte's reactivity system
    ✓ Type-Safe - Full TypeScript support with auto-completion
    ✓ Modular Architecture - Install only what you need
    ✓ Physics Engine - Built-in Rapier physics integration
    ✓ Animation Studio - Theatre.js integration for complex animations
    ✓ VR/AR Ready - WebXR support out of the box
    ✓ GLTF Support - CLI tool for model conversion
    ✓ Interactive - Built-in pointer events and interactivity
    ✓ Performance - Optimized for production use
    ✓ Flexible Layout - 3D flexbox layout engine
    ✓ Well Documented - Comprehensive docs and examples
  21. Step 21

    Community and Resources

    Links to official documentation, examples, and community resources.

    Official Documentation: https://threlte.xyz
    GitHub Repository: https://github.com/threlte/threlte
    Examples Gallery: https://threlte.xyz/docs/examples
    Discord Community: https://discord.gg/EqUBCfCaGm
    Twitter: @threlte
    
    Learning Resources:
    - Getting Started Guide: https://threlte.xyz/docs/learn/getting-started
    - API Reference: https://threlte.xyz/docs/reference
    - Interactive Examples: https://threlte.xyz/docs/examples
    - Community Tutorials: https://joyofcode.xyz/introduction-to-3d-with-svelte

Feature requests

Sign in to suggest features or vote on existing ones.

No feature requests yet.

Discussion

0 people marked this as worked·Sign in to mark your own.

Sign in to join the discussion.

No comments yet.