Найти в Дзене
Linux code

Three.js

Three.js — библиотека JavaScript, используется для создания и отображения анимированной компьютерной 3D графики.
сцена, созданная в three.js
сцена, созданная в three.js

Three.js — библиотека JavaScript, используется для создания и отображения анимированной компьютерной 3D графики.

  • Рендереры: Canvas, SVG или WebGL
  • Сцена: добавление и удаление объектов в режиме реального времени; туман
  • Камеры: перспективная или ортографическая
  • Анимация: каркасы, прямая кинематика, инверсная кинематика, покадровая анимация
  • Источники света: внешний, направленный, точечный; тени: брошенные и полученные
  • Шейдеры: полный доступ ко всем OpenGL-шейдерам (GLSL)
  • Объекты: сети, частицы, спрайты, линии, скелетная анимация и другое
  • Геометрия: плоскость, куб, сфера, тор, 3D текст и другое; модификаторы: ткань, выдавливание
  • Загрузчики данных: двоичный, изображения, JSON и сцена
  • Экспорт и импорт: утилиты, создающие Three.js-совместимые JSON файлы из форматов: Blender, openCTM, FBX, 3D Studio Max, и Wavefront .obj файл
  • Поддержка: документация по API библиотеки находится в процессе постоянного расширения и дополнения, есть публичный форум и обширное сообщество
  • Примеры: на официальном сайте можно найти более 150 примеров работы со шрифтами, моделями, текстурами, звуком и другими элементами сцены

Создание сцены

Для начала необходимо запустить локальный сервер. В качестве варианта - локальный сервер Python с помощью команды:

python3 -m http.server

Файл ./index,html:

<html>
<head>
<title>Earth three.js</title>
<style>
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%
}
</style>
</head>
<body>
<script
src="/files/libs/three.min.js"></script>
<script
src="/files/libs/CCapture.all.min.js"></script>
<script
src="/scripts/start.js" type="module"></script>
</body>
</html>

Файлы библиотек three.js и CCapture.js поместить в ./files/libs/

Файл ./scripts/start.js:

import {run} from './solar_system/earth/run.js';

run();

Файл ./scripts/solar_system/earth/run.js:

import {createScene, createCamera, createRender, createLightAmbient, createLightDirectional} from './base.js';
import {createEarth, createClouds, createStars} from './objects.js';

export function
run() {
let width = 1920;
let height = 1080;
let scene =
createScene();
let camera =
createCamera(width, height);
let render =
createRender(width, height);
let lightA =
createLightAmbient();
let lightB =
createLightDirectional();
let earth =
createEarth();
let clouds =
createClouds();
let stars =
createStars();
camera.position.z = 1.5;
scene.add(lightA);
scene.
add(lightA);
scene.
add(lightB);
scene.
add(earth);
scene.
add(clouds);
scene.
add(stars);

function
animate() {
earth.rotation.y += 0.0005;
clouds.rotation.y += 0.0005;
requestAnimationFrame(animate);
render.
render(scene, camera);
}

animate();
}

Файл ./scripts/solar_system/earth/base.js:

export function createScene() {
return new
THREE.Scene();
}

export function
createCamera(w, h) {
return new
THREE.PerspectiveCamera(75, w/h, 0.1, 1000);
}

export function
createRender(w, h) {
let render = new
THREE.WebGLRenderer();
render.
setSize(w, h);
document.body.
appendChild(render.domElement);
return render;
}

export function
createLightAmbient() {
return new
THREE.AmbientLight(0x333333);
}

export function
createLightDirectional() {
let light = new
THREE.DirectionalLight(0xffffff, 1);
light.position.
set(5,3,5);
return light;
}

Файл ./scripts/solar_system/earth/objects.js:

export function createEarth() {
let textureEarth = '/scripts/solar_system/earth/images/earth/4k.jpg';
let textureBump = '/scripts/solar_system/earth/images/bump/4k.jpg';
let textureWater = '/scripts/solar_system/earth/images/water/4k.png';

return new
THREE.Mesh(
new
THREE.SphereGeometry(0.5, 32, 32),
new
THREE.MeshPhongMaterial({
map: new
THREE.TextureLoader().load(textureEarth),
bumpMap: new
THREE.TextureLoader().load(textureBump),
bumpScale: 0.005,
specularMap: new
THREE.TextureLoader().load(textureWater),
specular: new
THREE.Color('grey')
})
);
}

export function
createClouds() {
let texture = '/scripts/solar_system/earth/images/clouds/4k.png';

return new
THREE.Mesh(
new
THREE.SphereGeometry(0.503, 32, 32),
new
THREE.MeshPhongMaterial({
map: new
THREE.TextureLoader().load(texture),
transparent: true
})
);
}

export function
createStars() {
let texture = '/scripts/solar_system/earth/images/galaxy/stars.png';
return new
THREE.Mesh(
new
THREE.SphereGeometry(90, 64, 64),
new
THREE.MeshBasicMaterial({
map: new
THREE.TextureLoader().load(texture),
side: THREE.BackSide
})
);
}

Текстуры:

  • earth : ./scripts/solar_system/earth/images/earth/4k.jpg
  • bump : ./scripts/solar_system/earth/images/bump/4k.jpg
  • water : ./scripts/solar_system/earth/images/water/4k.png
  • clouds : ./scripts/solar_system/earth/images/clouds/4k.png
  • stars : ./scripts/solar_system/earth/images/galaxy/stars.png