2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Three.jsを使ってみる①

Last updated at Posted at 2019-08-26

Three.jsとは?

three.jsは3次元コンピュータグラフィックスを描画するJavascriptのライブラリである. three.jsのページでは様々なサンプルが公開されており, 幅広い3DCGのプログラミングが可能なことがわかる.更にWebブラウザで動作するので手軽に始めることができる.

three.jsのダウンロード

ここのdownloadからthree.jsを取ってくる.

基本的な使い方

three.jsを記述する場所を決める

ここを参考にコーディングをしていく.

<!DOCTYPE html>
<html>
	<head>
		<meta charset=utf-8>
		<title>My first three.js app</title>
		<style>
			body { margin: 0; }
			canvas { width: 100%; height: 100% }
		</style>
	</head>
	<body>
		<script src="js/three.js"></script>
		<script>
			// ここにコードを書いていく
		</script>
	</body>
</html>

シーンの作成

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

//3DCGの描画範囲と場所を指定する
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

このコードでははじめにシーンを作成し, カメラを設置する.最後にレンダラーを作成する.今回はbodyに直接シーンを描画する.

オブジェクトを置く

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

ここでは, 箱型のジオメトリ(図形)を作成し, その箱の材質をを決めてシーンに追加している.最後にカメラ位置をz軸方向に5進めている.

アニメーションと描画

function animate() {
	requestAnimationFrame( animate );
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
	renderer.render( scene, camera );
}
animate();

ここでは先程設置した箱を回転させるアニメーションの作成と, シーンの描画をしている.

実行結果

Screenshot from 2019-08-27 01-10-38.png

箱が回転している.

おわりに

今回はthree.jsのチュートリアルに沿って進めていった.ここに使い方など詳しく書いてあるので, それを参考にしながら実際に触ることをおすすめする.続きの記事も書いていく予定.

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?