Babylon.js 安装与配置 #

安装方式概览 #

Babylon.js 提供了多种安装方式,适用于不同的开发场景:

text
┌─────────────────────────────────────────────────────────────┐
│                    安装方式选择指南                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  CDN 引入 ─────── 快速原型、学习测试                         │
│                                                             │
│  NPM 安装 ─────── 正式项目、模块化开发                       │
│                                                             │
│  CDN ES Module ── 现代 Web 项目                             │
│                                                             │
│  Playground ───── 在线开发、代码分享                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

方式一:CDN 引入 #

最简单的方式是直接通过 CDN 引入 Babylon.js。

基础版本 #

html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Babylon.js Demo</title>
  <style>
    html, body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    #renderCanvas {
      width: 100%;
      height: 100%;
      touch-action: none;
    }
  </style>
</head>
<body>
  <canvas id="renderCanvas"></canvas>
  
  <!-- 引入 Babylon.js 核心 -->
  <script src="https://cdn.babylonjs.com/babylon.js"></script>
  
  <!-- 引入加载器(支持 glTF、OBJ 等格式) -->
  <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
  
  <script>
    const canvas = document.getElementById('renderCanvas');
    const engine = new BABYLON.Engine(canvas, true);
    
    const createScene = function() {
      const scene = new BABYLON.Scene(engine);
      scene.clearColor = new BABYLON.Color4(0.1, 0.1, 0.2, 1);
      
      const camera = new BABYLON.ArcRotateCamera(
        'camera',
        Math.PI / 2,
        Math.PI / 2,
        5,
        BABYLON.Vector3.Zero(),
        scene
      );
      camera.attachControl(canvas, true);
      
      const light = new BABYLON.HemisphericLight(
        'light',
        new BABYLON.Vector3(1, 1, 0),
        scene
      );
      
      const sphere = BABYLON.MeshBuilder.CreateSphere(
        'sphere',
        { diameter: 1 },
        scene
      );
      
      return scene;
    };
    
    const scene = createScene();
    
    engine.runRenderLoop(function() {
      scene.render();
    });
    
    window.addEventListener('resize', function() {
      engine.resize();
    });
  </script>
</body>
</html>

CDN 资源列表 #

text
┌─────────────────────────────────────────────────────────────┐
│                    常用 CDN 资源                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  核心库:                                                    │
│  https://cdn.babylonjs.com/babylon.js                       │
│                                                             │
│  模型加载器:                                                │
│  https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js │
│                                                             │
│  GUI 系统:                                                  │
│  https://cdn.babylonjs.com/gui/babylon.gui.min.js           │
│                                                             │
│  物理引擎:                                                  │
│  https://cdn.babylonjs.com/cannon.js                        │
│  https://cdn.babylonjs.com/ammo.js                          │
│                                                             │
│  材质库:                                                    │
│  https://cdn.babylonjs.com/materialsLibrary/babylonjs.materials.min.js
│                                                             │
│  后处理:                                                    │
│  https://cdn.babylonjs.com/postProcessesLibrary/babylonjs.postProcess.min.js
│                                                             │
└─────────────────────────────────────────────────────────────┘

完整 CDN 示例 #

html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Babylon.js Full Demo</title>
  <style>
    html, body { margin: 0; padding: 0; width: 100%; height: 100%; }
    #renderCanvas { width: 100%; height: 100%; }
  </style>
</head>
<body>
  <canvas id="renderCanvas"></canvas>
  
  <!-- 核心库 -->
  <script src="https://cdn.babylonjs.com/babylon.js"></script>
  
  <!-- 模型加载器 -->
  <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
  
  <!-- GUI 系统 -->
  <script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
  
  <!-- 材质库 -->
  <script src="https://cdn.babylonjs.com/materialsLibrary/babylonjs.materials.min.js"></script>
  
  <script>
    // 你的代码...
  </script>
</body>
</html>

方式二:NPM 安装 #

对于正式项目,推荐使用 NPM 进行安装。

安装命令 #

bash
# 安装核心库
npm install @babylonjs/core

# 安装加载器(支持 glTF、OBJ 等)
npm install @babylonjs/loaders

# 安装 GUI 系统
npm install @babylonjs/gui

# 安装材质库
npm install @babylonjs/materials

# 安装后处理效果
npm install @babylonjs/post-processes

# 安装物理引擎
npm install @babylonjs/havok

项目结构 #

text
my-babylon-project/
├── src/
│   ├── index.ts
│   ├── scenes/
│   │   └── mainScene.ts
│   └── utils/
│       └── helpers.ts
├── public/
│   ├── index.html
│   └── models/
├── package.json
└── tsconfig.json

TypeScript 配置 #

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["ES2020", "DOM"],
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "declaration": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

ES Module 导入 #

typescript
// 核心导入
import { Engine, Scene, ArcRotateCamera, HemisphericLight, MeshBuilder, Vector3 } from '@babylonjs/core';

// 加载器导入
import '@babylonjs/loaders/glTF';

// GUI 导入
import { AdvancedDynamicTexture, Button, Control } from '@babylonjs/gui';

// 材质导入
import { GridMaterial } from '@babylonjs/materials';

// 创建引擎和场景
const canvas = document.getElementById('renderCanvas') as HTMLCanvasElement;
const engine = new Engine(canvas, true);
const scene = new Scene(engine);

// 创建相机
const camera = new ArcRotateCamera(
  'camera',
  Math.PI / 2,
  Math.PI / 2,
  5,
  Vector3.Zero(),
  scene
);
camera.attachControl(canvas, true);

// 创建光源
const light = new HemisphericLight(
  'light',
  new Vector3(1, 1, 0),
  scene
);

// 创建网格
const sphere = MeshBuilder.CreateSphere('sphere', { diameter: 1 }, scene);

// 渲染循环
engine.runRenderLoop(() => {
  scene.render();
});

// 窗口大小调整
window.addEventListener('resize', () => {
  engine.resize();
});

Vite 配置示例 #

typescript
import { defineConfig } from 'vite';

export default defineConfig({
  resolve: {
    alias: {
      '@': '/src'
    }
  },
  server: {
    port: 3000,
    open: true
  },
  build: {
    target: 'esnext',
    sourcemap: true
  }
});

Webpack 配置示例 #

javascript
const path = require('path');

module.exports = {
  entry: './src/index.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  }
};

方式三:ES Module CDN #

使用现代浏览器的 ES Module 支持:

html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Babylon.js ES Module</title>
  <style>
    #renderCanvas { width: 100%; height: 100vh; }
  </style>
</head>
<body>
  <canvas id="renderCanvas"></canvas>
  
  <script type="module">
    import * as BABYLON from 'https://cdn.babylonjs.com/babylon.max.js';
    
    const canvas = document.getElementById('renderCanvas');
    const engine = new BABYLON.Engine(canvas, true);
    
    const scene = new BABYLON.Scene(engine);
    
    const camera = new BABYLON.ArcRotateCamera(
      'camera',
      Math.PI / 2,
      Math.PI / 2,
      5,
      BABYLON.Vector3.Zero(),
      scene
    );
    camera.attachControl(canvas, true);
    
    const light = new BABYLON.HemisphericLight(
      'light',
      new BABYLON.Vector3(1, 1, 0),
      scene
    );
    
    const sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 1 }, scene);
    
    engine.runRenderLoop(() => scene.render());
    
    window.addEventListener('resize', () => engine.resize());
  </script>
</body>
</html>

方式四:Playground 在线开发 #

Babylon.js Playground 是官方提供的在线开发环境。

访问地址 #

text
https://playground.babylonjs.com/

Playground 特点 #

text
┌─────────────────────────────────────────────────────────────┐
│                    Playground 功能                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ✅ 即时预览                                                 │
│     - 代码修改立即生效                                       │
│     - 实时渲染结果                                           │
│                                                             │
│  ✅ 代码分享                                                 │
│     - 生成分享链接                                           │
│     - 嵌入到文档                                             │
│                                                             │
│  ✅ 调试工具                                                 │
│     - 内置 Inspector                                        │
│     - 性能分析                                               │
│                                                             │
│  ✅ 模板示例                                                 │
│     - 丰富的示例库                                           │
│     - 学习资源                                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Playground 示例代码 #

javascript
// Playground 默认模板
const createScene = function() {
  const scene = new BABYLON.Scene(engine);
  
  const camera = new BABYLON.ArcRotateCamera(
    'camera',
    -Math.PI / 2,
    Math.PI / 2.5,
    3,
    new BABYLON.Vector3(0, 0, 0),
    scene
  );
  camera.attachControl(canvas, true);
  
  const light = new BABYLON.HemisphericLight(
    'light',
    new BABYLON.Vector3(0, 1, 0),
    scene
  );
  
  const box = BABYLON.MeshBuilder.CreateBox('box', {}, scene);
  
  return scene;
};

开发工具配置 #

VS Code 扩展 #

推荐安装以下 VS Code 扩展:

text
┌─────────────────────────────────────────────────────────────┐
│                    推荐扩展                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. Babylon.js Playground                                   │
│     - 内联 Playground 支持                                   │
│     - 代码片段                                               │
│                                                             │
│  2. GLSL Lint                                               │
│     - 着色器语法高亮                                         │
│     - 错误检查                                               │
│                                                             │
│  3. TypeScript                                              │
│     - 类型检查                                               │
│     - 智能提示                                               │
│                                                             │
│  4. ESLint                                                  │
│     - 代码规范检查                                           │
│     - 自动修复                                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

VS Code settings.json #

json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "typescript.tsdk": "node_modules/typescript/lib",
  "files.associations": {
    "*.fx": "glsl"
  }
}

启用调试工具 #

javascript
// 启用 Inspector
scene.debugLayer.show({
  overlay: true,
  showExplorer: true,
  showInspector: true
});

// 隐藏 Inspector
scene.debugLayer.hide();

模块化开发 #

场景管理器 #

typescript
import { Engine, Scene, ArcRotateCamera, HemisphericLight, Vector3 } from '@babylonjs/core';

export class SceneManager {
  private engine: Engine;
  private scene: Scene;
  private canvas: HTMLCanvasElement;

  constructor(canvas: HTMLCanvasElement) {
    this.canvas = canvas;
    this.engine = new Engine(canvas, true, {
      preserveDrawingBuffer: true,
      stencil: true
    });
    this.scene = new Scene(this.engine);
  }

  init(): void {
    this.createCamera();
    this.createLight();
    this.startRenderLoop();
  }

  private createCamera(): void {
    const camera = new ArcRotateCamera(
      'camera',
      Math.PI / 2,
      Math.PI / 2,
      5,
      Vector3.Zero(),
      this.scene
    );
    camera.attachControl(this.canvas, true);
  }

  private createLight(): void {
    new HemisphericLight(
      'light',
      new Vector3(1, 1, 0),
      this.scene
    );
  }

  private startRenderLoop(): void {
    this.engine.runRenderLoop(() => {
      this.scene.render();
    });

    window.addEventListener('resize', () => {
      this.engine.resize();
    });
  }

  getScene(): Scene {
    return this.scene;
  }

  dispose(): void {
    this.scene.dispose();
    this.engine.dispose();
  }
}

资源加载器 #

typescript
import { SceneLoader, Scene, AbstractMesh } from '@babylonjs/core';
import '@babylonjs/loaders/glTF';

export class AssetLoader {
  constructor(private scene: Scene) {}

  async loadModel(url: string, fileName: string): Promise<AbstractMesh[]> {
    const result = await SceneLoader.ImportMeshAsync(
      '',
      url,
      fileName,
      this.scene
    );
    
    return result.meshes;
  }

  async loadGLTF(path: string): Promise<AbstractMesh[]> {
    return this.loadModel(path, '');
  }
}

常见问题解决 #

Canvas 尺寸问题 #

javascript
// 确保 canvas 有正确的尺寸
const canvas = document.getElementById('renderCanvas');

// CSS 样式
// #renderCanvas { width: 100%; height: 100vh; }

// 或者在 JavaScript 中设置
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 监听窗口大小变化
window.addEventListener('resize', () => {
  engine.resize();
});

WebGL 不支持 #

javascript
// 检查 WebGL 支持
function checkWebGLSupport() {
  try {
    const canvas = document.createElement('canvas');
    return !!(
      window.WebGLRenderingContext &&
      (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))
    );
  } catch (e) {
    return false;
  }
}

if (!checkWebGLSupport()) {
  alert('您的浏览器不支持 WebGL');
}

模型加载失败 #

javascript
// 使用正确的加载方式
BABYLON.SceneLoader.ImportMesh(
  '',
  'https://example.com/models/',  // 注意末尾斜杠
  'model.glb',
  scene,
  function(meshes) {
    console.log('模型加载成功', meshes);
  },
  function(evt) {
    // 加载进度
    const loadedPercent = (evt.loaded * 100 / evt.total).toFixed(2);
    console.log(`加载进度: ${loadedPercent}%`);
  },
  function(err) {
    // 加载错误
    console.error('模型加载失败', err);
  }
);

下一步 #

环境搭建完成后,接下来学习 场景基础,创建你的第一个 3D 场景!

最后更新:2026-03-29