3D with Svelte and Three.js

UPDATE: Since this article’s release, the example at GitHub has been updated to leverage SvelteKit.
Updating some demo apps, I wanted to build with something fast and lean — less boilerplate than React to add clarity to examples, yet with the power of live reload, package management, and bundling.
Interested in trying Svelte, I was surprised by the simplicity and cleanliness of the environment and toolchain.

Here’s an example incorporating Three.js to build a 3D WebGL app.
Follow along, or checkout the repository at GitHub.
Creating the Solution
First, scaffold the project using npx degit
to setup Svelte’s template by executing the following command in a terminal:
npx degit sveltejs/template svelte-app
Continue by adding the three
package:
npm add three
Npm will add Three.js and automatically install packages.
App.svelte
In App.svelte
create a canvas
element, and use Svelte’s bindings to link the DOM element to be passed into the createScene()
function.
Though Three.js can automatically create and append its own DOM element, it’s cool to see how Svelte can pass the element scoped in declarative syntax.
It’s important to note that this requires Svelte’s lifecycle method of onMount()
which runs after the component is first rendered to the DOM.
scene.js
Create a new file named scene.js
— we’ll put sample code from Three.js documentation of Creating a scene with a few minor alterations to address resizing the browser window:
In the code above, a scene
and camera
are used by the renderer
to update the canvas element each frame. The animate()
function executes Three.js rendering by requesting an animation frame from the browser’s next repaint.
Within this scene, a cube
mesh is added which is defined by geometry
and uses a material
to give an appearance to the mesh.
To handle resizing the browser window, a resize
event listener is added to update the camera and resize the canvas element on the page.
global.css
Finally, for visual appearance update the global.css
to fill the screen:
Launch It
From a terminal, execute npm run dev
to start Svelte’s live reload with Rollup, and open http://localhost:5000 to view the result.
In my next post, I’ll show an alternate version using the Babylon.js engine.
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: CoFeed | Differ
- More content at PlainEnglish.io