Skip to content

Instantly share code, notes, and snippets.

@tanish-kr
Created October 22, 2021 06:24
Show Gist options
  • Save tanish-kr/d524c1fa392437fb4fd1dfb79ec02705 to your computer and use it in GitHub Desktop.
Save tanish-kr/d524c1fa392437fb4fd1dfb79ec02705 to your computer and use it in GitHub Desktop.
threejs-example-firststep
<canvas id="threejs-canvas"></canvas>
window.addEventListener('load', init);
function init() {
const width = 960;
const height = 540;
// レンダラーを作成
// const renderer = new THREE.WebGLRenderer();
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('#threejs-canvas'),
//alpha: true
});
renderer.setSize(width, height); // 描画サイズをセット
renderer.setPixelRatio(window.devicePixelRatio); // ピクセル化
// const canvas = document.getElementById("threejs-canvas");
// canvas.appendChild(renderer.domElement);
// カメラを作成 (視野角, アスペクト比, カメラに映る最短距離, カメラに映る再遠距離)
const camera = new THREE.PerspectiveCamera(60, width / height, 1, 1000);
camera.position.z = 3; // カメラを遠ざける
// シーンを作成
const scene = new THREE.Scene();
// ライトを作成
const light = new THREE.PointLight(0xffffff);
light.position.set(2, 2, 2); // ライトの位置を設定
// ライトをシーンに追加
scene.add(light);
// 立方体のジオメトリを作成(幅、高さ、奥行き)
const geo = new THREE.BoxGeometry(1, 1, 1);
// マテリアルを作成
const material = new THREE.MeshLambertMaterial({ color: 0xffffff });
// ジオメトリとマテリアルからメッシュを作成
const mesh = new THREE.Mesh(geo, material);
mesh.rotation.x = Math.PI; // rotationの角度の単位はラジアンなので`Math.PI`を使って計算 (円周と直径の比率 3.14159...)
mesh.rotation.y = Math.PI / 2;
// TREEE.Math.DEG2RADで度数で指定可能
mesh.rotation.y = THREE.Math.DEG2RAD * 45;
mesh.rotation.x = THREE.Math.DEG2RAD * 45;
mesh.rotation.z = THREE.Math.DEG2RAD * 15;
// メッシュをシーンに追加
scene.add(mesh);
// const vec = new THREE.Vector3();
// mesh.getWorldPosition(vec);
// 座標軸を表示
const axis = new THREE.AxisHelper(300);
axis.position.set(40, 40, 40);
scene.add(axis);
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(50, 50, 0),
]);
const line = new THREE.Line(geometry, new THREE.LineBasicMaterial());
scene.add(line);
// 画面に表示
renderer.render(scene, camera);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment