Introduction to Babylon.js
Babylon.js is one of the most popular 3D game engines used by web developers. As with any other 3D library, it provides built-in functions that help you implement common 3D functionality more quickly and efficiently. In this guide, we'll take you through the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code to create your first 3D scene.
Babylon.js is a powerful, open-source WebGL engine that has established itself as a leading choice for creating 3D experiences in the browser. Whether you're building immersive games, product visualizations, architectural walkthroughs, or virtual reality experiences, Babylon.js provides the tools and abstractions needed to bring your ideas to life without getting bogged down in low-level WebGL complexity.
The engine handles all the heavy lifting of 3D rendering--the mathematics of projection, the management of materials and textures, the physics simulations--while exposing a clean, well-documented API that lets you focus on creating compelling content. With support for desktop browsers, mobile devices, and VR headsets, Babylon.js enables you to reach your audience wherever they are. Our web development services team specializes in building these interactive 3D experiences for clients across various industries.
Why Choose Babylon.js
- TypeScript Support: Built-in type definitions for better development experience and IDE autocompletion
- Excellent Documentation: Comprehensive official documentation and active community forums
- Cross-Platform: Consistent behavior across desktop and mobile browsers
- VR/XR Support: Built-in virtual reality capabilities with WebXR standard
- Performance: Optimized rendering pipeline for smooth experiences even on lower-end devices
Compared to other WebGL libraries like Three.js, Babylon.js offers a more opinionated structure that many developers find easier to learn, while still providing the flexibility needed for advanced projects. The engine's architecture separates concerns cleanly between scenes, cameras, lights, and meshes, making it intuitive to organize complex 3D applications.
Key concepts covered in this tutorial
Development Setup
Set up Babylon.js using CDN or npm for your projects
Scene Creation
Initialize the engine and create your first 3D scene
Camera Types
Add cameras to view your scene from different perspectives
Lighting
Illuminate objects with various light types
Geometry
Create 3D shapes including boxes, spheres, and planes
Materials & Textures
Apply colors and textures to make objects look realistic
Animation
Add movement with keyframe animations
Development Setup
Option 1: Using CDN
The quickest way to get started with Babylon.js is using a Content Delivery Network (CDN). This approach requires no build tools and is perfect for learning, prototyping, and simple projects. Simply add the Babylon.js script tag to your HTML, and the entire library is available through the global BABYLON namespace.
<script src="https://cdn.babylonjs.com/babylon.js"></script>
For specific features like model loading, you can add additional scripts:
<script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
The CDN approach is ideal when you want to experiment quickly or when building simple landing pages with 3D elements. However, for production applications where you need tree-shaking to reduce bundle size, npm installation is the better choice.
Option 2: Local Development with NPM
For production applications, installing Babylon.js via npm provides better dependency management, build tool integration, and the ability to use modern ES6 modules.
npm install babylonjs
For tree-shaking support with modern bundlers like Webpack or Vite, use the scoped packages:
npm install @babylonjs/core @babylonjs/loaders @babylonjs/materials @babylonjs/gui
Additional NPM Packages
Beyond the core engine, Babylon.js offers specialized packages for common requirements:
- @babylonjs/loaders: Support for importing 3D models in formats like .glb, .gltf, .obj, and .fbx
- @babylonjs/materials: Advanced PBR materials and procedural textures
- @babylonjs/gui: Complete GUI system for creating 2D interfaces within 3D scenes
- @babylonjs/inspector: Runtime debugging and scene inspection tools
- @babylonjs/procedural-textures: Library of procedurally generated textures
Choose the CDN approach for quick experimentation and learning, or npm for production applications where you need fine-grained control over your bundle size and build process.
The Babylon.js Playground
The Babylon.js Playground is the single most important tool for learning and developing with Babylon.js. This interactive environment allows you to write Babylon.js code on the left panel and see results instantly on the right panel--no setup required. The Playground eliminates the friction of creating HTML files, configuring build tools, and refreshing browsers, letting you focus entirely on learning and experimenting.
For beginners, the Playground provides an ideal learning environment where you can modify existing examples and see immediate results. The extensive template library, accessible with CTRL+SPACE, gives you starting points for common scenarios. Need to see how a specific camera works? Find a camera template and experiment with the parameters. Want to understand materials? Start with a material template and play with the properties.
Keyboard Shortcuts:
- ALT+ENTER: Run or re-run your code
- CTRL+S: Save your playground to a permanent URL
- CTRL+SPACE: Open the template menu
- CTRL+SHIFT+F: Format your code
The Playground also serves as a powerful sharing and collaboration tool. When you encounter an issue or have a question, you can create a minimal reproducible example in the Playground and share the URL with others. This makes getting help from the community much easier, as others can immediately see and modify your code. Many questions on the Babylon.js Forum are answered with Playground links demonstrating the solution.
Beyond learning, the Playground is excellent for rapid prototyping. Before committing to a particular approach in your project, test it in the Playground. This rapid iteration cycle helps you validate ideas quickly without the overhead of a full development environment. The saved playgrounds also serve as a personal library of examples you can reference when building production applications.
HTML Structure for Babylon.js
Every Babylon.js application needs a canvas element and proper HTML structure. The canvas serves as the rendering surface where WebGL draws your 3D content. Here's a complete template that covers all the essentials:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Babylon.js Demo</title>
<style>
html, body, canvas {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
</style>
</head>
<body>
<canvas id="renderCanvas" touch-action="none"></canvas>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<script>
// Your Babylon.js code here
</script>
</body>
</html>
Key HTML Elements
The canvas element is the heart of any Babylon.js application. It must have an ID that your JavaScript code can reference, and it should fill the available viewport space. The touch-action: none CSS property and attribute are critical for mobile devices--they prevent the browser from handling touch gestures, allowing Babylon.js to capture them for camera control and other interactions instead.
The CSS ensures the canvas takes the full width and height of the viewport while removing default margins and scrollbars. The overflow: hidden on the html and body elements prevents scrollbars from appearing even if content exceeds the viewport, which is important for full-screen 3D experiences.
For production applications, you might also want to consider accessibility. Adding ARIA labels to the canvas and providing fallback content for users who cannot see the 3D content ensures your applications are usable by a wider audience. While these considerations are beyond the scope of a basic tutorial, they become important when building commercial or public-facing applications.
Initializing the Engine and Creating a Scene
Creating the Engine
The Babylon.js engine is the core component that handles rendering. It manages the WebGL context, coordinates the rendering loop, and provides the bridge between your code and the GPU. Initialize it with a reference to your canvas element:
const canvas = document.getElementById("render-canvas");
const engine = new BABYLON.Engine(canvas, true);
The second parameter (true in this case) enables antialiasing, which produces smoother edges on 3D objects. This parameter is optional but often desirable for a polished look.
Creating a Scene
A scene is a container for all your 3D content. Think of it as a stage where cameras, lights, meshes, and materials perform together. Every Babylon.js application needs at least one scene, and you create one by passing the engine as a parameter:
const scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8);
The clearColor property sets the background color of your scene. This appears in areas where no objects are rendered, essentially acting as your sky color. The Color3 class takes RGB values from 0 to 1, so (0.8, 0.8, 0.8) creates a light gray background.
Creating the Render Loop
The render loop continuously draws your scene to the canvas. Without it, you would see only a single frame. The runRenderLoop method registers a function that runs on every animation frame:
engine.runRenderLoop(function () {
scene.render();
});
Handling Window Resize
When users resize their browser window, the canvas dimensions change, and the engine needs to update its internal state accordingly. The resize handler is essential for maintaining proper aspect ratios and preventing distortion:
window.addEventListener("resize", function () {
engine.resize();
});
Without this handler, your 3D scene would appear stretched or compressed if the window size changes, and in some cases might not render at all. This is particularly important for full-screen applications where users might resize their browser or rotate their device.
Creating a Camera
Cameras define the viewpoint from which your scene is rendered. Without a camera, nothing would be visible. Babylon.js offers several camera types designed for different use cases, from first-person exploration to object inspection.
FreeCamera
The FreeCamera provides unrestricted movement through the scene, allowing the viewer to fly in any direction. It's named "free" because it doesn't constrain movement to any particular path:
const camera = new BABYLON.FreeCamera(
"camera",
new BABYLON.Vector3(0, 0, -10),
scene
);
The parameters are: the camera's name (for reference), its initial position as a Vector3, and the scene. The FreeCamera works well for first-person games or applications where users need to navigate freely through 3D space.
ArcRotateCamera
The ArcRotateCamera orbits around a target point, making it ideal for viewing and inspecting objects from different angles. This is the most commonly used camera for product visualizations, model viewers, and applications where you want users to rotate around a central object:
const camera = new BABYLON.ArcRotateCamera(
"camera",
-Math.PI / 2, // alpha (horizontal rotation angle)
Math.PI / 2.5, // beta (vertical rotation angle)
10, // radius (distance from target)
BABYLON.Vector3.Zero(), // target point to orbit around
scene
);
camera.attachControl(canvas, true); // Enable user interaction
The alpha parameter controls horizontal rotation around the target (measured in radians from the positive X axis). The beta parameter controls vertical rotation, where 0 is directly above and PI is directly below the target. The attachControl method connects the camera to user input, allowing mouse drag and scroll wheel on desktop, and touch gestures on mobile devices.
Camera controls can be further customized with panning sensitivity, zoom limits, and rotation speed. The ArcRotateCamera is often preferred for demos and product viewers because it provides an intuitive orbit interaction that users immediately understand.
Adding Lights
Lights illuminate your 3D objects and create depth and dimension. Without light, objects appear as flat silhouettes regardless of how detailed their geometry or materials are. Babylon.js provides several light types, each simulating a different real-world lighting scenario.
PointLight
A PointLight emits light from a single point in all directions, similar to a light bulb. Objects closer to the light appear brighter, while those further away receive less illumination:
const light = new BABYLON.PointLight(
"light",
new BABYLON.Vector3(10, 10, 0),
scene
);
light.intensity = 0.8;
PointLights are useful for creating localized lighting effects, such as lamps, torches, or any light source with a specific position in your scene.
HemisphericLight
A HemisphericLight simulates ambient environment lighting, providing a quick way to illuminate your entire scene with minimal configuration. It doesn't have a specific position--instead, it lights everything from a general direction:
const light = new BABYLON.HemisphericLight(
"light",
new BABYLON.Vector3(1, 1, 0), // direction (up and toward positive X and Z)
scene
);
light.intensity = 0.7;
The HemisphericLight is often used as the primary light source in simple scenes because it provides even, shadow-free illumination that ensures objects are always visible.
DirectionalLight and SpotLight
For more specialized lighting, the DirectionalLight simulates sunlight or other distant light sources, casting parallel rays in a specific direction. The SpotLight creates a cone of light, useful for flashlights, stage lights, or any focused illumination.
Light Properties
All light types share common properties:
- intensity: Controls brightness (default is 1.0; values above 1 create brighter light, below 1 create dimmer light)
- diffuse: The color of the light's direct illumination (affects object colors when lit)
- specular: The color of shiny reflections (creates highlights on shiny surfaces)
Choosing the right light type depends on your scene's requirements. For simple demos and prototypes, start with a HemisphericLight for overall illumination, then add PointLights or DirectionalLights for highlights and shadows.
Creating 3D Geometry
Babylon.js provides many built-in shapes that can be created with a single line of code. These primitives form the building blocks of more complex 3D objects.
Creating a Box
The simplest 3D shape is a box (or cube), created with the MeshBuilder:
const box = BABYLON.MeshBuilder.CreateBox("box", { size: 2 }, scene);
box.position.y = 1;
The options object controls the box's dimensions. { size: 2 } creates a cube 2 units on each side. The position.y places the box on top of the ground rather than intersecting it.
Creating a Sphere
Spheres are useful for creating balls, planets, or any rounded objects:
const sphere = BABYLON.MeshBuilder.CreateSphere(
"sphere",
{ diameter: 2, segments: 32 },
scene
);
sphere.position.x = 3;
The diameter parameter controls the sphere's size, while segments determines smoothness. Higher values create smoother spheres but require more processing power.
Creating a Ground Plane
Ground planes provide a surface for objects to rest on:
const ground = BABYLON.MeshBuilder.CreateGround(
"ground",
{ width: 10, height: 10 },
scene
);
Other Shapes
Beyond these basics, Babylon.js offers many additional shapes:
- CreateCylinder: Creates cylinders and can be tapered to make cones
- CreateTorus: Creates donut or ring shapes
- CreateDisc: Creates flat circular shapes
- CreatePolyhedron: Creates Platonic solids (tetrahedron, octahedron, etc.)
- CreateTorusKnot: Creates complex knotted shapes
- CreateTube: Creates tubular shapes along a path
Manipulating Position and Rotation
All meshes share common transformation properties:
box.position.x = 1;
box.position.y = 0.5;
box.position.z = 0;
box.rotation.x = Math.PI / 4; // 45 degrees
box.rotation.y = -Math.PI / 6; // -30 degrees
box.rotation.z = 0;
box.scaling.x = 1.5; // Scale to 150% on X axis
box.scaling.y = 0.5; // Scale to 50% on Y axis
box.scaling.z = 1; // No change on Z axis
Position, rotation, and scaling can be set individually or all at once using Vector3 objects. These transformations are fundamental to arranging your 3D scene and creating interesting compositions.
Adding Materials
Materials define how surfaces look and how they react to light. Without materials, meshes appear as simple silhouettes with no color or shading. Babylon.js offers several material types for different rendering needs.
StandardMaterial
The StandardMaterial is the most commonly used material type and supports colors, textures, and various lighting effects:
const material = new BABYLON.StandardMaterial("material", scene);
material.diffuseColor = new BABYLON.Color3(0.2, 0.6, 1); // Blue
box.material = material;
The diffuseColor is the base color that appears under direct lighting--it's what most people think of as the "color" of an object.
Color Properties
StandardMaterial supports several color properties:
- diffuseColor: The base color affected by direct light (most visible)
- emissiveColor: Self-illuminated color that appears even in darkness
- specularColor: The color of shiny highlights (creates the glossy look)
- ambientColor: The color in shadow areas
material.emissiveColor = new BABYLON.Color3(0.1, 0.1, 0.2); // Subtle glow
material.specularColor = new BABYLON.Color3(1, 1, 1); // White highlights
Adding Textures
For more realistic surfaces, apply textures instead of solid colors:
const texture = new BABYLON.Texture("path/to/image.jpg", scene);
material.diffuseTexture = texture;
Textures can represent wood grain, metal surfaces, fabric patterns, or any surface detail. You can layer multiple textures for more complex effects, using the diffuse texture for color and other textures for bump mapping, specular highlights, and more.
Other Material Types
For advanced rendering, Babylon.js offers:
- PBRMaterial: Physically Based Rendering materials for realistic, production-quality surfaces
- NodeMaterial: Visual material editor for complex shader effects without writing code
- ShaderMaterial: Custom shaders for unique visual effects
- GridMaterial: Specialized material for ground and wireframe effects
PBR materials are increasingly popular for product visualizations and games because they simulate how light interacts with real-world materials based on physical properties like roughness and metallicness.
Adding Animation
Animation brings your 3D scenes to life with movement and change. Babylon.js provides a powerful animation system based on keyframes, allowing you to animate virtually any property of any object.
Creating a Keyframe Animation
The Animation class defines an animation for a specific property. Here's a rotation animation:
const animationBox = new BABYLON.Animation(
"rotationAnimation",
"rotation.y",
30, // frames per second
BABYLON.Animation.ANIMATIONTYPE_FLOAT,
BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE
);
const keys = [];
keys.push({ frame: 0, value: 0 });
keys.push({ frame: 100, value: Math.PI * 2 });
animationBox.setKeys(keys);
box.animations.push(animationBox);
scene.beginAnimation(box, 0, 100, true);
The parameters are: animation name, the property to animate, frame rate, data type, and loop mode. The keyframes define the property's value at specific frames, and Babylon.js interpolates between them.
Animation Parameters
- property: The property to animate, using dot notation for nested properties (e.g., "position.x", "scaling.z")
- frameRate: Animation speed in frames per second (30 fps is a good starting point)
- valueType: Data type of the animated property (FLOAT, VECTOR3, QUATERNION, COLOR3, etc.)
- loopMode: How the animation repeats (CYCLE loops forever, CONSTANT plays once, CYCLE_RELATIVE loops with offset)
Position Animation
You can animate any property, including position for moving objects:
const positionAnim = new BABYLON.Animation(
"positionAnimation",
"position.x",
30,
BABYLON.Animation.ANIMATIONTYPE_FLOAT,
BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE
);
const posKeys = [];
posKeys.push({ frame: 0, value: -5 });
posKeys.push({ frame: 50, value: 5 });
posKeys.push({ frame: 100, value: -5 });
positionAnim.setKeys(posKeys);
sphere.animations.push(positionAnim);
scene.beginAnimation(sphere, 0, 100, true);
Scaling Animation
For pulsing or growing effects, animate the scaling:
const scalingAnim = new BABYLON.Animation(
"scalingAnimation",
"scaling",
30,
BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE
);
const scaleKeys = [];
scaleKeys.push({ frame: 0, value: new BABYLON.Vector3(1, 1, 1) });
scaleKeys.push({ frame: 50, value: new BABYLON.Vector3(1.5, 1.5, 1.5) });
scaleKeys.push({ frame: 100, value: new BABYLON.Vector3(1, 1, 1) });
scalingAnim.setKeys(scaleKeys);
box.animations.push(scalingAnim);
scene.beginAnimation(box, 0, 100, true);
Animation Methods
- beginAnimation: Start animation on a mesh with specified parameters
- beginDirectAnimation: More control over animation execution
- pause(): Pause a running animation
- restart(): Resume a paused animation
- stop(): Stop an animation entirely
The animation system supports complex timelines with multiple animations running simultaneously on the same or different objects, enabling sophisticated animated sequences.
1const canvas = document.getElementById("render-canvas");2const engine = new BABYLON.Engine(canvas, true);3 4const createScene = function () {5 const scene = new BABYLON.Scene(engine);6 scene.clearColor = new BABYLON.Color3(0.9, 0.9, 0.95);7 8 // Camera9 const camera = new BABYLON.ArcRotateCamera(10 "camera",11 -Math.PI / 2,12 Math.PI / 2.5,13 10,14 BABYLON.Vector3.Zero(),15 scene16 );17 camera.attachControl(canvas, true);18 19 // Light20 const light = new BABYLON.HemisphericLight(21 "light",22 new BABYLON.Vector3(1, 1, 0),23 scene24 );25 light.intensity = 0.7;26 27 // Box28 const box = BABYLON.MeshBuilder.CreateBox("box", { size: 2 }, scene);29 box.position.y = 1;30 31 // Material32 const material = new BABYLON.StandardMaterial("material", scene);33 material.diffuseColor = new BABYLON.Color3(0.2, 0.6, 1);34 box.material = material;35 36 // Animation37 const animationBox = new BABYLON.Animation(38 "rotation",39 "rotation.y",40 30,41 BABYLON.Animation.ANIMATIONTYPE_FLOAT,42 BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE43 );44 45 const keys = [];46 keys.push({ frame: 0, value: 0 });47 keys.push({ frame: 100, value: Math.PI * 2 });48 animationBox.setKeys(keys);49 box.animations.push(animationBox);50 scene.beginAnimation(box, 0, 100, true);51 52 return scene;53};54 55const scene = createScene();56engine.runRenderLoop(function () {57 scene.render();58});59window.addEventListener("resize", function () {60 engine.resize();61});Next Steps and Further Learning
Congratulations on building your first Babylon.js scene! You've covered the fundamentals that form the foundation of any Babylon.js project. Now it's time to explore more advanced capabilities that will take your 3D applications to the next level.
Advanced Topics
-
Physics Engine: Add realistic physics with Cannon.js or Ammo.js integration. Enable gravity, collisions, and physical responses to create interactive environments where objects fall, bounce, and collide realistically.
-
VR/XR Support: Create immersive virtual reality experiences with Babylon.js's built-in WebXR support. Build VR product configurators, architectural walkthroughs, or training simulations that users can experience with headsets. Our AI automation services can help integrate intelligent features into your VR experiences.
-
Particle Systems: Add fire, smoke, rain, sparks, and other atmospheric effects. Particle systems can create everything from magical spells to weather effects to enhance your scenes.
-
Importing Models: Load 3D models created in Blender, Maya, Cinema 4D, or other tools. The SceneLoader supports formats like .glb, .gltf, .obj, and .fbx, enabling you to use professional art assets.
-
GUI Elements: Add buttons, text labels, sliders, and other interface elements to your 3D scenes. Create heads-up displays, interactive controls, and information panels.
-
Post-Processing: Apply effects like Post-Processing blur, glow, depth of field, and color grading. Post-processing chains can dramatically enhance the visual quality of your scenes.
Learning Resources
- Babylon.js Documentation - Comprehensive guides covering every feature
- Babylon.js Playground - Interactive examples to learn from
- Babylon.js Forum - Active community for getting help
- Official Tutorials - Deep-dive guides on specific features
For your next project, consider exploring our web development services to build production-ready 3D applications, or learn more about custom web applications that integrate 3D experiences with business logic and data systems. If you're interested in creating interactive product visualizations, our e-commerce development team can help you build immersive shopping experiences that drive conversions.