Создание интерактивных трехмерных сцен средствами Three.js

Раздел: Веб-разработка -> 3D графика

Three.js в веб-разработке: базовые и альтернативные подходы

Three.js представляет собой библиотеку для работы с 3D-графикой в браузере через WebGL и WebGPU. Она скрывает сложность низкоуровневых API и дает удобные абстракции: сцена, камера, рендерер, геометрии, материалы, свет, контроллеры, загрузчики. Ниже описан основной практический подход, затем альтернативные варианты с вопросами и разбором типичных ситуаций.

Основной подход: модульная сборка с Vite и npm

Наиболее управляемый способ для реального проекта: установка Three.js через npm, сборка через Vite, импорт ES-модулей, отдельный слой сцены и цикл рендера. Такой вариант дает контроль версий, tree-shaking, dev-сервер и понятную структуру.

npm create vite@latest three-app -- --template vanilla\ncd three-app\nnpm install three\nnpm run dev

три js (three.js (3d графика))

Файл main.js может выглядеть так:

import * as THREE from 'three';\n\nconst scene = new THREE.Scene();\nscene.background = new THREE.Color(0x101820);\n\nconst camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 1000);\ncamera.position.set(2, 2, 4);\n\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\nrenderer.setPixelRatio(Math.min(devicePixelRatio, 2));\ndocument.body.appendChild(renderer.domElement);\n\nconst geometry = new THREE.BoxGeometry(1, 1, 1);\nconst material = new THREE.MeshStandardMaterial({ color: 0x4caf50, roughness: 0.4 });\nconst mesh = new THREE.Mesh(geometry, material);\nscene.add(mesh);\n\nconst light = new THREE.DirectionalLight(0xffffff, 2);\nlight.position.set(3, 4, 2);\nscene.add(light);\nscene.add(new THREE.AmbientLight(0xffffff, 0.4));\n\nfunction onResize() {\n  camera.aspect = innerWidth / innerHeight;\n  camera.updateProjectionMatrix();\n  renderer.setSize(innerWidth, innerHeight);\n}\naddEventListener('resize', onResize);\n\nfunction tick(time) {\n  mesh.rotation.y = time * 0.001;\n  renderer.render(scene, camera);\n  requestAnimationFrame(tick);\n}\nrequestAnimationFrame(tick);

Babylon js (библиотека babylon.js для 3d)

Шаги: создание сцены, камеры и рендерера; добавление объекта и света; обработка изменения размеров; запуск цикла requestAnimationFrame. Для управления камерой часто применяется OrbitControls из examples/jsm/controls/OrbitControls.js.

Типичная ошибка:

объект не виден из-за камеры в начале координат или из-за отсутствия света. В MeshStandardMaterial без света поверхность выглядит черной. Решение: расположить камеру на расстоянии, добавить AmbientLight и DirectionalLight, проверить near и far.

Как подключить Three.js без сборщика через CDN?

Вариант подходит для прототипов, демо, CodePen, обучения и небольших страниц. Используется import map, который связывает имя модуля three с URL CDN. Такой подход не требует npm и Vite.

<script type='module'>\nimport * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';\nimport { OrbitControls } from 'https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js';\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(0, 1, 3);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\n\nconst controls = new OrbitControls(camera, renderer.domElement);\nconst mesh = new THREE.Mesh(\n  new THREE.TorusKnotGeometry(0.7, 0.2, 100, 16),\n  new THREE.MeshNormalMaterial()\n);\nscene.add(mesh);\n\nrenderer.setAnimationLoop(() => {\n  controls.update();\n  renderer.render(scene, camera);\n});\n</script>

Цель: быстрый старт без инфраструктуры. Ограничение: зависимость от внешнего CDN и отсутствие оптимизации сборки.

Проблема: import map должен идти до модульного скрипта. Если браузер не поддерживает import maps, загрузка модулей нарушается. Для старых браузеров применяется сборщик или полифил.

Как организовать сцену при росте проекта?

Для больших приложений полезна архитектура с классами или модулями: отдельно renderer, scene, camera, controls, assets, animation. Это упрощает повторное использование и тестирование.

// app/SceneManager.js\nimport * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nexport class SceneManager {\n  constructor(container) {\n    this.scene = new THREE.Scene();\n    this.camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 200);\n    this.camera.position.set(4, 3, 6);\n    this.renderer = new THREE.WebGLRenderer({ antialias: true });\n    this.renderer.setSize(container.clientWidth, container.clientHeight);\n    this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2));\n    container.appendChild(this.renderer.domElement);\n    this.controls = new OrbitControls(this.camera, this.renderer.domElement);\n  }\n  add(object) { this.scene.add(object); }\n  resize(width, height) {\n    this.camera.aspect = width / height;\n    this.camera.updateProjectionMatrix();\n    this.renderer.setSize(width, height);\n  }\n  render() {\n    this.controls.update();\n    this.renderer.render(this.scene, this.camera);\n  }\n}

Цель: разделение ответственности. Такой код проще расширять, подключать UI и управлять жизненным циклом.

Проблема: утечки памяти при удалении сцены. Геометрии, материалы, текстуры и renderer требуют вызова dispose. При переходе между экранами важно удалять слушатели и останавливать animation loop.

Как загружать GLTF и GLB модели?

GLTF и GLB являются распространенными форматами для 3D-контента. Three.js содержит GLTFLoader в examples/jsm/loaders/GLTFLoader.js.

import * as THREE from 'three';\nimport { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';\n\nconst loader = new GLTFLoader();\nloader.load('/models/robot.glb', (gltf) => {\n  const model = gltf.scene;\n  model.scale.set(0.8, 0.8, 0.8);\n  scene.add(model);\n\n  const mixer = new THREE.AnimationMixer(model);\n  const action = mixer.clipAction(gltf.animations[0]);\n  action.play();\n\n  function tick(delta) {\n    mixer.update(delta);\n  }\n}, undefined, (error) => {\n  console.error('Ошибка загрузки модели', error);\n});

Цель: использование готовых моделей из Blender, Maya, Spline и других редакторов. Для сжатых моделей применяется DRACOLoader или MeshoptDecoder.

Проблема: модель не появляется из-за неверного пути, CORS или отсутствия текстур. Для GLB текстуры встроены, для GLTF они лежат рядом. При DRACO-сжатии нужен декодер и настройка loader.setDRACOLoader.

Как добавить интерактивность через Raycaster?

Raycaster определяет пересечение луча из камеры с объектами сцены. Это основа выбора объектов мышью или касанием.

const raycaster = new THREE.Raycaster();\nconst pointer = new THREE.Vector2();\n\nrenderer.domElement.addEventListener('pointerdown', (event) => {\n  const rect = renderer.domElement.getBoundingClientRect();\n  pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n  pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n  raycaster.setFromCamera(pointer, camera);\n  const hits = raycaster.intersectObjects(scene.children, true);\n  if (hits.length > 0) {\n    hits[0].object.material.color.set(0xff5722);\n  }\n});

Цель: выделение, перетаскивание, подсказки, игровые механики. Для сложных сцен применяется слои или фильтрация по массиву интерактивных объектов.

Проблема: неверные координаты при CSS-масштабировании canvas или devicePixelRatio. Решение: использовать getBoundingClientRect и корректно переводить координаты в NDC.

Какой рендерер выбрать: WebGLRenderer или WebGPURenderer?

WebGLRenderer имеет широкую поддержку и стабильность. WebGPURenderer находится в развитии и дает доступ к новому API, compute shaders и лучшей производительности в поддерживаемых браузерах.

import * as THREE from 'three';\nimport WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';\n\nconst renderer = new WebGPURenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\n\nrenderer.setAnimationLoop(() => {\n  renderer.render(scene, camera);\n});

Цель: WebGL применяется для максимальной совместимости, WebGPU для экспериментов и задач с compute. Для продакшена часто нужен fallback.

Проблема: WebGPU доступен не во всех браузерах и требует HTTPS. Импорт может отличаться в разных версиях Three.js. При отсутствии поддержки создается WebGLRenderer.

Как повысить производительность сцены?

Основные приемы: объединение геометрий, InstancedMesh для множества одинаковых объектов, LOD, ограничение pixelRatio, отключение ненужных обновлений matrixAutoUpdate, контроль количества источников света и текстур.

const geometry = new THREE.SphereGeometry(0.2, 16, 16);\nconst material = new THREE.MeshStandardMaterial({ color: 0x2196f3 });\nconst count = 1000;\nconst mesh = new THREE.InstancedMesh(geometry, material, count);\nconst matrix = new THREE.Matrix4();\n\nfor (let i = 0; i < count; i++) {\n  const x = (Math.random() - 0.5) * 20;\n  const y = (Math.random() - 0.5) * 20;\n  const z = (Math.random() - 0.5) * 20;\n  matrix.makeTranslation(x, y, z);\n  mesh.setMatrixAt(i, matrix);\n}\nmesh.instanceMatrix.needsUpdate = true;\nscene.add(mesh);

Цель: рост FPS при большом числе объектов. InstancedMesh снижает количество draw calls.

Проблема: обновление матриц каждого экземпляра в цикле рендера без необходимости. Решение: менять instanceMatrix только при изменении позиций и выставлять needsUpdate.

Как работать с текстурами и цветовым пространством?

С версии r152 цветовое управление стало строже. Для цветных текстур указывается SRGBColorSpace, для данных нормалей и roughness остается NoColorSpace или LinearSRGBColorSpace.

const textureLoader = new THREE.TextureLoader();\nconst map = textureLoader.load('/textures/albedo.jpg');\nmap.colorSpace = THREE.SRGBColorSpace;\nmap.anisotropy = renderer.capabilities.getMaxAnisotropy();\n\nconst material = new THREE.MeshStandardMaterial({\n  map,\n  roughness: 0.6,\n  metalness: 0.1\n});

Цель: корректные цвета и четкость под углом. Anisotropy улучшает качество на наклонных поверхностях.

Проблема: слишком темные или пересвеченные текстуры из-за неверного colorSpace. Для normalMap нельзя ставить SRGBColorSpace.

Итог: базовый путь связан с npm, Vite и модульной архитектурой. Альтернативы зависят от задачи: CDN для прототипа, классы для масштаба, GLTF для моделей, Raycaster для интерактива, WebGPU для экспериментов, InstancedMesh и правильные текстуры для производительности.

Расширенные примеры Three.js с кодом и результатом

Пример 1: ShaderMaterial с волновой деформацией

Пользовательский шейдер управляет смещением вершин и освещением. В примере время передается через uniform uTime.

Пример
import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(0, 1.5, 4);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\nnew OrbitControls(camera, renderer.domElement);\n\nconst uniforms = {\n  uTime: { value: 0 },\n  uColor: { value: new THREE.Color(0x00bcd4) }\n};\n\nconst material = new THREE.ShaderMaterial({\n  uniforms,\n  vertexShader: `\n    uniform float uTime;\n    varying vec3 vNormal;\n    void main() {\n      vNormal = normal;\n      vec3 pos = position;\n      pos += normal * sin(pos.y * 4.0 + uTime) * 0.08;\n      gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n    }\n  `,\n  fragmentShader: `\n    uniform vec3 uColor;\n    varying vec3 vNormal;\n    void main() {\n      float light = dot(normalize(vNormal), normalize(vec3(0.5, 1.0, 0.3))) * 0.5 + 0.5;\n      gl_FragColor = vec4(uColor * light, 1.0);\n    }\n  `\n});\n\nconst mesh = new THREE.Mesh(new THREE.SphereGeometry(1, 128, 128), material);\nscene.add(mesh);\n\nrenderer.setAnimationLoop((time) => {\n  uniforms.uTime.value = time * 0.001;\n  renderer.render(scene, camera);\n});
Пульсирующая сфера с волнами по нормалям, управляемая uniform uTime.

Пример 2: InstancedMesh с цветом каждого экземпляра и Raycaster

InstancedMesh рисует тысячи объектов за один draw call. Цвет задается через instanceColor, а выбор работает по instanceId.

Пример
import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 200);\ncamera.position.set(0, 0, 20);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\nnew OrbitControls(camera, renderer.domElement);\nscene.add(new THREE.AmbientLight(0xffffff, 1));\nconst dir = new THREE.DirectionalLight(0xffffff, 2);\ndir.position.set(5, 10, 7);\nscene.add(dir);\n\nconst count = 2000;\nconst geometry = new THREE.IcosahedronGeometry(0.12, 0);\nconst material = new THREE.MeshStandardMaterial({ roughness: 0.3, metalness: 0.1 });\nconst mesh = new THREE.InstancedMesh(geometry, material, count);\nconst dummy = new THREE.Object3D();\nconst color = new THREE.Color();\n\nfor (let i = 0; i < count; i++) {\n  dummy.position.set((Math.random() - 0.5) * 30, (Math.random() - 0.5) * 30, (Math.random() - 0.5) * 30);\n  dummy.rotation.set(Math.random() * Math.PI, Math.random() * Math.PI, Math.random() * Math.PI);\n  dummy.updateMatrix();\n  mesh.setMatrixAt(i, dummy.matrix);\n  color.setHSL(Math.random(), 0.7, 0.5);\n  mesh.setColorAt(i, color);\n}\nmesh.instanceMatrix.needsUpdate = true;\nmesh.instanceColor.needsUpdate = true;\nscene.add(mesh);\n\nconst raycaster = new THREE.Raycaster();\nconst pointer = new THREE.Vector2();\nrenderer.domElement.addEventListener('pointerdown', (event) => {\n  pointer.x = (event.clientX / innerWidth) * 2 - 1;\n  pointer.y = -(event.clientY / innerHeight) * 2 + 1;\n  raycaster.setFromCamera(pointer, camera);\n  const hit = raycaster.intersectObject(mesh)[0];\n  if (hit) {\n    mesh.setColorAt(hit.instanceId, new THREE.Color(0xff0000));\n    mesh.instanceColor.needsUpdate = true;\n  }\n});\n\nrenderer.setAnimationLoop(() => {\n  mesh.rotation.y += 0.002;\n  renderer.render(scene, camera);\n});
2000 цветных многогранников, выбранный экземпляр становится красным.

Пример 3: Постобработка с EffectComposer и UnrealBloomPass

Постобработка добавляется поверх сцены. Bloom создает свечение вокруг ярких участков.

Пример
import * as THREE from 'three';\nimport { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';\nimport { RenderPass } from 'three/addons/postprocessing/RenderPass.js';\nimport { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);\ncamera.position.set(0, 1, 4);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\n\nconst geometry = new THREE.TorusKnotGeometry(0.8, 0.25, 200, 32);\nconst material = new THREE.MeshStandardMaterial({ color: 0x00e5ff, emissive: 0x006064, roughness: 0.2 });\nconst mesh = new THREE.Mesh(geometry, material);\nscene.add(mesh);\nscene.add(new THREE.PointLight(0xffffff, 30));\nscene.add(new THREE.AmbientLight(0xffffff, 0.3));\n\nconst composer = new EffectComposer(renderer);\ncomposer.addPass(new RenderPass(scene, camera));\nconst bloom = new UnrealBloomPass(new THREE.Vector2(innerWidth, innerHeight), 1.2, 0.6, 0.1);\ncomposer.addPass(bloom);\n\nrenderer.setAnimationLoop(() => {\n  mesh.rotation.y += 0.01;\n  mesh.rotation.x += 0.004;\n  composer.render();\n});
Светящийся торус с эффектом bloom и мягким ореолом.

Пример 4: CubeCamera для динамических отражений

CubeCamera обновляет кубическую текстуру окружения. Материал с metalness и roughness использует ее как envMap.

Пример
import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nconst scene = new THREE.Scene();\nscene.background = new THREE.Color(0x111111);\nconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 1000);\ncamera.position.set(4, 3, 6);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\nnew OrbitControls(camera, renderer.domElement);\nscene.add(new THREE.AmbientLight(0xffffff, 0.4));\nconst light = new THREE.DirectionalLight(0xffffff, 3);\nlight.position.set(5, 8, 4);\nscene.add(light);\n\nconst cubeRenderTarget = new THREE.WebGLCubeRenderTarget(256, {\n  generateMipmaps: true,\n  minFilter: THREE.LinearMipmapLinearFilter\n});\nconst cubeCamera = new THREE.CubeCamera(0.1, 1000, cubeRenderTarget);\ncubeCamera.position.set(0, 1, 0);\nscene.add(cubeCamera);\n\nconst sphere = new THREE.Mesh(\n  new THREE.SphereGeometry(1, 64, 64),\n  new THREE.MeshStandardMaterial({ color: 0xffffff, metalness: 1, roughness: 0, envMap: cubeRenderTarget.texture })\n);\nscene.add(sphere);\n\nconst moving = new THREE.Mesh(\n  new THREE.BoxGeometry(1, 1, 1),\n  new THREE.MeshStandardMaterial({ color: 0xff9800, emissive: 0x442200 })\n);\nscene.add(moving);\n\nrenderer.setAnimationLoop((time) => {\n  moving.position.x = Math.sin(time * 0.001) * 3;\n  moving.rotation.y += 0.02;\n  sphere.visible = false;\n  cubeCamera.update(renderer, scene);\n  sphere.visible = true;\n  renderer.render(scene, camera);\n});
Зеркальная сфера отражает движущийся куб и обновляемое окружение.

Пример 5: Система частиц на Points с пользовательским шейдером

Points рисует множество точек. Шейдер управляет размером, прозрачностью и волновым смещением.

Пример
import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 200);\ncamera.position.set(0, 0, 25);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\nnew OrbitControls(camera, renderer.domElement);\n\nconst count = 5000;\nconst positions = new Float32Array(count * 3);\nconst sizes = new Float32Array(count);\nfor (let i = 0; i < count; i++) {\n  positions[i * 3] = (Math.random() - 0.5) * 50;\n  positions[i * 3 + 1] = (Math.random() - 0.5) * 50;\n  positions[i * 3 + 2] = (Math.random() - 0.5) * 50;\n  sizes[i] = Math.random() * 2 + 0.5;\n}\n\nconst geometry = new THREE.BufferGeometry();\ngeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));\ngeometry.setAttribute('aSize', new THREE.BufferAttribute(sizes, 1));\n\nconst material = new THREE.ShaderMaterial({\n  uniforms: { uTime: { value: 0 } },\n  vertexShader: `\n    attribute float aSize;\n    uniform float uTime;\n    varying float vAlpha;\n    void main() {\n      vec3 pos = position;\n      pos.y += sin(uTime + pos.x * 0.5) * 0.5;\n      vec4 mv = modelViewMatrix * vec4(pos, 1.0);\n      gl_PointSize = aSize * (300.0 / -mv.z);\n      gl_Position = projectionMatrix * mv;\n      vAlpha = 0.5 + 0.5 * sin(uTime + pos.z);\n    }\n  `,\n  fragmentShader: `\n    varying float vAlpha;\n    void main() {\n      vec2 c = gl_PointCoord - vec2(0.5);\n      float d = length(c);\n      if (d > 0.5) discard;\n      gl_FragColor = vec4(0.4, 0.8, 1.0, vAlpha * (1.0 - d * 2.0));\n    }\n  `,\n  transparent: true,\n  depthWrite: false\n});\n\nconst points = new THREE.Points(geometry, material);\nscene.add(points);\n\nrenderer.setAnimationLoop((time) => {\n  material.uniforms.uTime.value = time * 0.001;\n  renderer.render(scene, camera);\n});
Плавающие синие частицы с волновым движением и мягкими краями.

Пример 6: LOD для переключения детализации

LOD автоматически выбирает уровень геометрии в зависимости от расстояния до камеры.

Пример
import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\n\nconst scene = new THREE.Scene();\nconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 1000);\ncamera.position.set(0, 2, 10);\nconst renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\nnew OrbitControls(camera, renderer.domElement);\nscene.add(new THREE.AmbientLight(0xffffff, 0.8));\nconst light = new THREE.DirectionalLight(0xffffff, 2);\nlight.position.set(3, 5, 4);\nscene.add(light);\n\nconst lod = new THREE.LOD();\nconst high = new THREE.Mesh(new THREE.IcosahedronGeometry(1, 5), new THREE.MeshStandardMaterial({ color: 0x4caf50 }));\nconst mid = new THREE.Mesh(new THREE.IcosahedronGeometry(1, 2), new THREE.MeshStandardMaterial({ color: 0xffc107 }));\nconst low = new THREE.Mesh(new THREE.IcosahedronGeometry(1, 0), new THREE.MeshStandardMaterial({ color: 0xf44336 }));\nlod.addLevel(high, 0);\nlod.addLevel(mid, 8);\nlod.addLevel(low, 15);\nscene.add(lod);\n\nrenderer.setAnimationLoop(() => {\n  lod.rotation.y += 0.005;\n  lod.update(camera);\n  renderer.render(scene, camera);\n});
Объект меняет детализацию при приближении и удалении камеры.

Three.js (3D графика) - comments

En
три js (javascript)