Содержание блога
Пример я переписал на TypeScript из официальной документации, отсюда: https://threejs.org/docs/#manu... ng-a-scene
Песочница на TypeScript
Исходники в архиве
Исходники на GitHub
Исходные файлы
package.json
| JSON | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| {
"name": "getting-started-with-threejs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"debug": "tsc -p tsconfig.debug.json",
"compile": "tsc -p tsconfig.release.json",
"bundle": "browserify public/js/Program.js -o public/js/bundle.js",
"minify": "uglifyjs public/js/bundle.js -o public/js/bundle.min.js",
"release": "npm run compile && npm run bundle && npm run minify"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"three": "^0.106.2"
},
"devDependencies": {
"@types/requirejs": "^2.1.31"
}
} |
|
tsconfig.debug.json
| JSON | 1
2
3
| {
"extends": "./tsconfig.json"
} |
|
tsconfig.release.json
| JSON | 1
2
3
4
5
6
7
| {
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"sourceMap": false
}
} |
|
style.css
| CSS | 1
2
3
4
5
6
7
8
| body {
margin: 0;
}
canvas {
width: 100%;
height: 100%
} |
|
index.html
| PHP/HTML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three.js - Getting Started</title>
<link rel="stylesheet" href="css/style.css">
<!-- Debug and Playground-Plunker Version -->
<script data-main="js/RequireConfig"
src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<!-- Release Version -->
<!-- <script src="js/bundle.min.js"></script> -->
</head>
<body>
</body>
</html> |
|
Game.ts
| JavaScript | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| import * as THREE from "three";
export class Game
{
private _cube: THREE.Mesh;
private _renderer: THREE.WebGLRenderer;
private _scene: THREE.Scene;
private _camera: THREE.PerspectiveCamera;
public constructor()
{
this._scene = new THREE.Scene();
this._camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this._camera.position.z = 5;
this._renderer = new THREE.WebGLRenderer();
this._renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this._renderer.domElement);
let geometry = new THREE.BoxGeometry(1, 1, 1);
let material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
this._cube = new THREE.Mesh(geometry, material);
this._scene.add(this._cube);
}
public Animate(): void
{
requestAnimationFrame(() => this.Animate());
this._cube.rotation.x += 0.1;
this._cube.rotation.y += 0.1;
this._renderer.render(this._scene, this._camera);
}
} |
|
Program.ts
| JavaScript | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| import { Game } from "./Game";
// Playground: https://next.plnkr.co/edit/YXLIamSsUH8k1E3r?preview
class Program
{
public static Main(): void
{
let game = new Game();
game.Animate();
}
}
// Debug and Playground-Plunker Version
Program.Main();
// Release Version
// window.onload = () => Program.Main(); |
|
RequireConfig.ts
| JavaScript | 1
2
3
4
5
6
7
8
| requirejs.config({
baseUrl: "js",
paths: {
"three": "https://cdnjs.cloudflare.com/ajax/libs/three.js/106/three.min"
}
});
requirejs(["Program"], (Program) => { }); |
|
launch.json
| JSON | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}/public"
}
]
} |
|
В начале, стоит отметить, что есть корень проекта, где лежит файл package.json. В этом файле перечислены модули, которые нужно поставить:
| JSON | 1
2
3
4
5
6
7
8
| {
"dependencies": {
"three": "^0.106.2"
},
"devDependencies": {
"@types/requirejs": "^2.1.31"
}
} |
|
Ставятся эти два модуля одной командой выполненной из корня проекта:
Либо, кратко: npm i
Нужно установить глобально модуль typescript. Делается это один раз:
Далее, нужно поставить локальный сервер. Я использую http-server. Ставится этот модуль глобально, один раз:
Запускаем из консоли в корневой папке проекта локальный сервер:
Переходим в браузер и в адресной строке набираем:
Запустится веб приложение.
Когда вы изменили код и решили перекомпилировать, то нужно ввести команду:
Переходите в браузер Chrome, открываете консоль разработчика (Ctrl+Shift+J), нажимаете правой кнопкой мыши по значку "Перегрузить" (в левом верхнем углу браузера - круговая стрелка), выбираете "Empty Cache and Hard Reload"
Попробуйте выполнить эту пошаговую инструкцию. Сообщите, какой шаг вызвал затруднение, или какой шаг инструкции содержит ошибку.
|