Getting Started with Three.js in SvelteKit

AuthorGormery

By: Gormery

Published: 11/1/2023

Updated: 1/10/2024

Scroll to read expand_more
Getting Started with Three.js in SvelteKit

It is possible to edit this blog post. Please login to edit.

SvelteKit and Three.js are powerful tools that can be combined to create impressive 3D graphics and interactive experiences right in your web applications. In this tutorial, we'll walk you through the process of integrating Three.js into your SvelteKit project and creating a simple 3D scene.

Prerequisites

Before we begin, make sure you have the following set up:

Setting Up the Project

First, let's create a new SvelteKit project and navigate to its root directory in the terminal:

bash
1npx degit sveltejs/template my-threejs-project
2cd my-threejs-project

Next, install the three package, use your preferred package manager:

bash
1pnpm install three

Types always help,but if not just remove remove the type definitions, and you should be good to go. so let's install the @types/three package as well:

undefined
1pnpm install -D @types/three

Creating a Basic 3D Scene

In your SvelteKit project, create a new Svelte component, let's call it ThreeScene.svelte:

html
1
2<script lang="ts">
3  // Import required modules
4  import { browser } from '$app/environment'
5  import { onMount } from 'svelte'
6  import * as THREE from 'three'
7
8  // Declare a variable to hold the container element
9  let canvasContainer: any
10
11  // Check if the code is running in the browser environment
12  if (browser) {
13    // Declare variables for Three.js components
14    let camera: THREE.PerspectiveCamera
15    let scene: THREE.Scene
16    let renderer: THREE.WebGLRenderer
17    let cube: THREE.Mesh<THREE.BoxGeometry, THREE.MeshBasicMaterial>
18
19    // Run this code when the component is mounted
20    onMount(() => {
21      // Create a Three.js scene, camera, and renderer
22      scene = new THREE.Scene()
23      camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000) // Aspect ratio set to 1 initially, the first parameter is the field of view, the second is the aspect ratio, the third is the near clipping plane, and the fourth is the far clipping plane
24      renderer = new THREE.WebGLRenderer()
25
26      // Calculate initial canvas size based on the container
27      const canvasWidth = canvasContainer.clientWidth
28      const canvasHeight = canvasContainer.clientHeight
29
30      // Set renderer size and add Tailwind classes to make it responsive
31      renderer.setSize(canvasWidth, canvasHeight)
32      renderer.domElement.classList.add('w-full', 'h-full')
33
34      // Append renderer's canvas to the container
35      canvasContainer.appendChild(renderer.domElement)
36
37      // Create a cube geometry and material, add it to the scene
38      const geometry = new THREE.BoxGeometry(1, 1, 1)
39      const material = new THREE.MeshBasicMaterial({ color: 0x66ccff }) // Blue color
40      cube = new THREE.Mesh(geometry, material)
41      scene.add(cube)
42
43      // Set camera position
44      camera.position.z = 5
45
46      // Start the animation loop
47      animate()
48    })
49
50    // Function to render the scene
51    const render = () => {
52      renderer.clear()
53      renderer.render(scene, camera)
54    }
55
56    // Animation loop
57    const animate = () => {
58      requestAnimationFrame(animate)
59
60      // Rotate the cube
61      cube.rotation.x += 0.05
62      cube.rotation.y += 0.05
63
64      // Update the camera's aspect ratio and position
65      camera.aspect = canvasContainer.clientWidth / canvasContainer.clientHeight
66      camera.updateProjectionMatrix()
67
68      // Render the scene
69      render()
70    }
71  }
72</script>
73
74<svelte:head>
75  <title>SvelteKit + Three.js</title>
76</svelte:head>
77<div class="flex flex-col items-center justify-center">
78  <h1 class="text-3xl font-bold mb-6 text-center">SvelteKit + Three.js</h1>
79  <p class="text-center">This is a demo of how to use Three.js with SvelteKit. The cube below is rendered using Three.js.</p>
80  <section bind:this={canvasContainer} class="w-36 h-36 flex justify-center items-center">
81    <!-- The canvas element will be appended here -->
82  </section>
83</div>

Running the Project

To run the project, use the following command:

bash
1pnpm run dev

You should see a cube rendered on the page:

sorry SvelteKit-Three-js.png image does not exist rotating cube of how the image will look like in the route

Conclusion

In this tutorial, we explored how to integrate Three.js into a SvelteKit project to create a simple 3D scene. This is just the beginning – Three.js offers a wide range of possibilities for creating stunning 3D visuals and interactive experiences in your web applications.

Now that you have a basic understanding of how to get started with Three.js in SvelteKit, feel free to experiment, explore the Three.js documentation, and take your 3D web development skills to the next level!

For more advanced features and optimizations, make sure to dive deeper into both SvelteKit and Three.js documentation.

Happy coding!

Join the Discussion

avatar
dracula
nice
avatar
Gormery
hey
avatar
undefined
ㅁㄴㅇㄹ
avatar
undefined
remark
avatar
users_valiantlynx96569
hello
avatar
undefined
avatar
undefined
hello
avatar
undefined
avatar
users_valiantlynx83722
hello
avatar
Gormery
shecker
avatar
undefined
lol
avatar
users_valiantlynx96569
Yoyoyo!!!