この手順をすると以下のものができます。
手順:
-
three.jsを導入する任意の repository を準備する (説明省略)
-
node をPCに install (説明省略)
-
npm の準備
npm init -y
-
buildツール: vite の準備
npm i vite
-
package.json
にvite コマンドのaliasを登録package.json...省略 "scripts": { "dev": "vite", "build": "vite build" }, ...省略
-
index.html
の作成- projectフォルダのルートに
index.html
を作成する -
index.html
をvscodeで開き、!
を打ち込む - すると、scaffold 機能でindex.htmlのテンプレートを自動生成できる
- projectフォルダのルートに
現在のリポジトリ状態
* (root)
* node_modules
+ * index.html
* pacakage-lock.json
* package.json
* README.md
- three.jsを使えるようにするために
script.js
を作成する
script.js
console.log("Hello, World!");
現在のリポジトリ状態
* (root)
* node_modules
* index.html
* pacakage-lock.json
* package.json
* README.md
+ * script.js
-
html
にjavascriptを読み込ませるために以下のようにする
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
+ <script type="module" src="./script.js"></script>
</body>
</html>
- three.js の準備
npm i three
- script.js にてthree.jsを読み込み、ログを出して確認する
script.js
+ import * as THREE from "three";
+ console.log(THREE);
- console.log("Hello, World!");
-
index.html
にて描画用のcanvasを準備する
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
+ <canvas class="webgl"></canvas>
<script type="module" src="./script.js"></script>
</body>
</html>
-
script.js
にて描画内容を作成する
script.js
import * as THREE from "three";
// Createb a canvas element
const canvas = document.querySelector("canvas.webgl");
// Create a scene
const scene = new THREE.Scene();
// Create a camera
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
// Create a renderer
const renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create a cube
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Animation loop
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
console.log(THREE);
参考
https://threejs-journey.com/lessons/what-is-webgl-and-why-use-three-js
https://threejs-journey.com/lessons/first-threejs-project