Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

3D with Svelte and Babylon.js

--

As a followup to my last post on 3D with Svelte and Three.js, here’s a similar example incorporating Svelte with the Babylon.js engine.

Follow along, or checkout the repository on 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 babylonjs package:

npm add babylonjs

Npm will add Babylon.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.

App.svelte

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 mirror a similar scene as in the Three.js example, but adapted for Babylon using sample code for their Getting Started GitHub Usage documentation.

scene.js

In the code above, the Babylon engine is instantiated to the canvas. A scene, camera, and light are setup leveraging an automatic rotation camera controller to orbit around the scene.

Within this scene, a cube mesh is built, and a material is applied to give an appearance to the mesh.

Rendering each frame of the animation uses Babylon engine’s built-in runRenderLoop() function.

To handle resizing the browser window, a resize event listener is added to update the engine to the new canvas size.

global.css

Finally, for visual appearance update the global.css to fill the screen:

global.css

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.

Use the mouse to orbit around the scene.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Written by Jason Sturges

Avant-garde experimental artist — creative professional leveraging technology for immersive experiences

No responses yet

Write a response