Threlte in Threejs

Threlte

Threlte is a Svelte library that simplifies creating 3D apps for the web. It provides a declarative, type-safe, reactive and interactive API out-of-the-box.

Threlte’s 3D rendering is powered by Three.js, and it also provides a physics engine through Rapier and an animation studio via Theatre.js

Threlte is comprised of six distinct packages to allow you to import only what you need:

As a first step we’re creating a new Svelte file called App.svelte where we are importing the <Canvas> component.

App.svelte

<script>
  import { Canvas } from '@threlte/core'
  import Scene from './Scene.svelte'
</script>
<Canvas>
  <Scene />
</Canvas>

The <Canvas> component is the root component of your Threlte application. It creates a renderer and sets up some sensible defaults for you like antialiasing and color management. It also creates a default camera and provides the context in which your Threlte application will run. For improving access to this runtime context, it’s best practice to create a seperate component called Scene.svelte and including it in our App.svelte file.

Creating Objects

At this point we’re looking at a blank screen. Let’s add a simple cube to it.

In Scene.svelte, we’re importing the <T> component which is the main building block of your Threlte application. It’s a generic component that we use to render any Three.js object. In this case we’re creating a THREE.Mesh which is made up from a THREE.BoxGeometry and a THREE.MeshBasicMaterial.

We should now be looking at a white cube on a transparent background.

Scene.svelte

Copy

<script>
  import { T } from '@threlte/core'
</script>
<T.Mesh>
  <T.BoxGeometry />
  <T.MeshBasicMaterial />
</T.Mesh>

we’re using the property attach available on <T> to attach an object to a property of its parent. Binding geometries to the property geometry and materials to the property material is a common pattern so Threlte takes care of it for you.

Leave a comment

Your email address will not be published. Required fields are marked *