Three.js start
by uto usui
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.5/dat.gui.min.js"></script>
<canvas id="canvas"></canvas>
SCSS
body {
overflow: hidden;
}
JavaScript
const init = () => {
// サイズ
const width = window.innerWidth;
const height = window.innerHeight;
// レンダラー
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('#canvas')
});
// retina
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(width, height);
// 背景色
renderer.setClearColor(new THREE.Color(0x121212));
// シーンを作成
const scene = new THREE.Scene();
// カメラを作成
const camera = new THREE.PerspectiveCamera(45, width / height, .1, 10000);
camera.position.set(0, 0, +1000);
// x y z軸のガイド
const axes = new THREE.AxesHelper(300);
scene.add(axes);
// 平行光源
const directionalLight = new THREE.DirectionalLight(0xFFFFFF);
directionalLight.position.set(0, 0, 1000);
// シーンに追加
scene.add(directionalLight);
// 形状
const geometry = new THREE.BoxGeometry(160, 90, 90);
const material = new THREE.MeshStandardMaterial(.1);
// オブジェクトとマテリアルをまとめる
const mesh = new THREE.Mesh(geometry, material);
// シーンに追加
scene.add(mesh);
// dat.GUI
const controls = new function() {
this.rotationSpeedX = 0.01;
this.rotationSpeedY = 0.01;
};
const gui = new dat.GUI();
gui.add(controls, 'rotationSpeedX', 0, 0.4);
gui.add(controls, 'rotationSpeedY', 0, 0.4);
// マウスイベント
// X座標に追従
let r = 0;
let mouseX = 0;
document.addEventListener('mousemove', (e) => {
mouseX = e.pageX;
});
// 描画を更新してアニメーション
const tick = () => {
// マウスの位置の値を角度に変換
const targetR = (mouseX / width) * 360;
// イージング
r += (targetR - r) * 0.04;
// ラジアンに変換する
const radian = r * Math.PI / 180;
// 角度に応じてカメラの位置を設定
camera.position.x = 1000 * Math.sin(radian);
camera.position.z = 1000 * Math.cos(radian);
// 原点方向を見る
camera.lookAt(new THREE.Vector3(0, 0, 0));
// 回転
mesh.rotation.x += controls.rotationSpeedX;
mesh.rotation.y += controls.rotationSpeedY;
renderer.render(scene, camera);
// 最適なFPSで描画
requestAnimationFrame(tick);
};
...