Blogブログ
広告
#JavaScript
【three.js】3Dデータ読み込み・背景色の変更・canvas外のスクロール制御(r171対応ver)

みなさま、ご無沙汰しております。
ほぼ1年ぶりの更新になってしまいました。。。
書こう書こうと思っていたんですが、日々の忙しさに追われ気づけば1年経っておりました。
僕は生きております!!
さて、今回3Dイメージを使用したウェブサイト制作の依頼があり、three.jsを使用し自分がつまずいた点をまとめましたので、同じく悩んでいる方のお力になれればと思っています!
three.jsの読み込み
Three.js公式サイトまたはGitHubリポジトリから最新リリース(r171)をダウンロードします。
リポジトリ内のbuild/three.module.jsがES Modules用のメインファイルとなります。また、examples/jsmディレクトリ以下に各種コントローラーやローダーなどのモジュールが格納されています。
project-root/
├─ public/
│ ├─ index.html
│ ├─ three/
│ │ ├─ build/three.module.js
│ │ ├─ examples/jsm/controls/OrbitControls.js
│ │ └─ examples/jsm/loaders/GLTFLoader.js
│ └─ ...
- three.module.js
- OrbitControls.js
- GLTFLoader.js
上記のファイルをサーバーサーバーにアップしてください。
3Dデータの読み込み
<script type="module">
import * as THREE from './three/build/three.module.js';
import { OrbitControls } from './three/examples/jsm/controls/OrbitControls.js';
import { ColladaLoader } from './three/examples/jsm/loaders/ColladaLoader.js';
// ページの読み込み完了時に初期化
window.addEventListener('load', init);
function init() {
// サイズを指定
const width = 960;
const height = 540;
// レンダラーを作成
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('#myCanvas'),
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
// シーンを作成
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x404040);
// カメラを作成
const camera = new THREE.PerspectiveCamera(
45,
width / height,
0.1,
10000
);
// カメラの初期座標を設定
camera.position.set(60, 0, 100);
// カメラコントローラーを作成 (renderer.domElementを渡す)
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, -5, 0);
controls.update();
// 平行光源を作成
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// 環境光を追加
const ambientLight = new THREE.AmbientLight(0x333333);
scene.add(ambientLight);
// Colladaモデルデータを読み込む
const loader = new ColladaLoader();
// Colladaファイルのパスを指定(相対パスまたは絶対パス)
loader.load('path/to/model.dae', collada => {
// 読み込み後に3D空間に追加
const model = collada.scene;
scene.add(model);
});
// アニメーションループ
function tick() {
renderer.render(scene, camera);
requestAnimationFrame(tick);
}
tick();
}
</script>
53行目の「path/to/model.dae」を.daeデータまでのパスに変更してください。
背景色の変更方法
19行目にある
scene.background = new THREE.Color( 0x404040 );
404040 部分を任意の色に変更する。
canvas外のスクロール制御
37行目にある
const controls = new OrbitControls(camera);
の部分を
const controls = new OrbitControls(camera, renderer.domElement);
に変更する。
まとめ
なかなか使う機会がないと思いますが、忘れないようにメモとして見ていただければと思います。
参考にさせていただいた記事
SHARE記事をシェアする
広告