Three.js で地球を回してみるテスト
○○で地球を回してみるシリーズ。
今回は、WebGL のライブラリの1つである「Three.js」用いて実現したいと思います。
0. 事前準備
WebGL に対応したブラウザ(任意のブラウザ)とライブラリ「Three.js」を用意します。
1. ソースを作成する
- earth.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello, Three.js World!</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="http://jsdo.it/lib/three.js-r60/js"></script> </head> <body> <div id="container"></div> <script type="text/javascript" src="earth.js"></script> </body> </html>
- style.css
* { margin: 0; padding: 0; border: 0; overflow: hidden; } body { background: #000; }
- earth.js
var container; var camera; var scene; var geometry; var material; var mesh; var renderer; init(); animate(); function init() { container = document.getElementById('container'); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000); camera.position.z = 400; scene = new THREE.Scene(); geometry = new THREE.SphereGeometry(150, 30, 30); material = new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('earth.jpg') }); mesh = new THREE.Mesh(geometry, material); mesh.overdraw = true; scene.add(mesh); renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); container.appendChild(renderer.domElement); } function animate() { requestAnimationFrame(animate); render(); } function render() { mesh.rotation.y += 0.005; renderer.render(scene, camera); }
前回の、WebGL を用いたプログラムに比べて、コード量が大分少なくすんでいることが分かります。
ちなみに、テクスチャの画像ファイルは、前回と同じく「earth.jpg」です。
2. ローカルで実行してみる
ブラウザにて earth.html を開きます。
- IE での実行結果
- Firefox での実行結果
3. jsdo.it で実行してみる
はてなブログが IE10 の互換性モードを指定している為、WebGL が表示できないようです。IE11 の場合は、別ウィンドウで開いてみてください。
参考
■ three.js - JavaScript 3D library
■ mrdoob three.js - GitHub
http://github.com/mrdoob/three.js/
■ HTML5 Canvas WebGL Sphere with Three.js
http://www.html5canvastutorials.com/three/html5-canvas-webgl-sphere-with-three-js/
■ Webグラフィックをハックする(5):多彩な表現力のWebGLを扱いやすくする「Three.js」 (1/5) - @IT