Three.js リサイズ
今回は、Three.jsのリサイズについて書きます。
リサイズは、ウィンドウのサイズを変更することです。
実行後に、画面のサイズをマウスとかで変更しても、自動でサイズを合わせます。
実装方法を書いていきます。
こちらは、青い球を表示するプログラムです。
<!DOCTYPE html> <html> <head> <title>introduction</title> <meta charset="utf-8"> <script src="three.min.js"></script> <script src="OrbitControls.js"></script> </head> <body onload="threeStart();" , style="overflow: hidden;"> <div id="ThreeJS" style="z-index: 1; position: absolute; left:0px; top:0px"></div> <script> var renderer; function initThree() { renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setClearColor(0xFFFFFF, 1); renderer.setSize(window.innerWidth,window.innerHeights); var container = document.getElementById( 'ThreeJS' ); container.appendChild( renderer.domElement ); } var camera; var controls; function initCamera() { camera = new THREE.PerspectiveCamera( 45 , window.innerWidth / window.innerHeight, 1 , 10000 ); camera.up.x = 0; camera.up.y = 0; camera.up.z = 1; camera.position.set(0, 150, 400); controls = new THREE.OrbitControls(camera,renderer.domElement); } var scene; function initScene() { scene = new THREE.Scene(); } var light, light2; function initLight() { light = new THREE.DirectionalLight(0xcccccc,1.6); light.position = new THREE.Vector3(-100, 500, 800); scene.add(light); light2 = new THREE.AmbientLight(0x333333); scene.add(light2); } var cube; function initObject(){ var cube = new THREE.Mesh( new THREE.SphereGeometry( 100, 50, 50 ), new THREE.MeshPhongMaterial({ color: 0x00FF7 })); scene.add(cube); cube.position.set(0,30,0); } function loop(){ requestAnimationFrame(loop); controls.update(); renderer.clear(); renderer.render(scene, camera); } function threeStart() { initThree(); initScene(); initCamera(); initLight(); initObject(); loop(); } window.addEventListener('resize', function() { renderer.setSize(window.innerWidth, window.innerHeight); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); }, false ); </script> </body> </html>
ここからは、補足説明を書きます。
①
余白をなくし、描画領域が、ページ読み込み時のウィンドウサイズに合うように調整しています。
<div id="ThreeJS" style="z-index: 1; position: absolute; left:0px; top:0px"></div>
②
window.addEventListener()の呼び出しは、リサイズへの対応です。
resizeイベントの発生時に、レンダラーのサイズとカメラのアスペクト比を再設定し、updateProjectMatrix()メソッドでカメラの内部状態を更新しています。
window.addEventListener('resize', function() { renderer.setSize(window.innerWidth, window.innerHeight); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); }, false );
これで終わりです。
ご不明な点などがありましたら、遠慮なくご質問ください。
ありがとうございました!