キューブ付きのシンプルなthree.jsシーンを作成するために、必要なすべての機能を1つのクラスに設定しようとしました。私はエラーはありませんが、ブラウザで開くとシーンが黒く表示されます。 は、ここに私のコードです:クラス内の3つのjs
class SceneInit {
constructor(fov = 45,camera,scene,controls,renderer)
{
this.camera = camera;
this.scene = scene;
this.controls = controls;
this.renderer = renderer;
this.fov = fov;
}
initScene() {
this.camera = new THREE.PerspectiveCamera(this.fov, window.innerWidth/window.innerHeight, 1, 1000);
this.camera.position.z = 15;
this.controls = new THREE.TrackballControls(this.camera);
//this.controls.addEventListener('change', this.renderScene);
this.scene = new THREE.Scene();
//specify a canvas which is already created in the HTML file and tagged by an id //aliasing enabled
this.renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myThreeJsCanvas') , antialias: true});
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this.renderer.domElement);
//ambient light which is for the whole scene
let ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
ambientLight.castShadow = false;
this.scene.add(ambientLight);
//spot light which is illuminating the chart directly
let spotLight = new THREE.SpotLight(0xffffff, 0.55);
spotLight.castShadow = true;
spotLight.position.set(0,40,10);
this.scene.add(spotLight);
//if window resizes
window.addEventListener('resize', this.onWindowResize, false);
}
animate(){
requestAnimationFrame(this.animate.bind(this));
this.render();
this.controls.update();
}
render(){
this.renderer.render(this.scene, this.camera);
}
onWindowResize() {
this.camera.aspect = window.innerWidth/window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
}
そして私は、新しいオブジェクトをインスタンス化し、シーンにオブジェクトを追加してみてください。シーンの子を印刷しようとすると、正しいオブジェクトが返されますが、前に述べたように、シーンは黒いままです。レンダラウィンドウだけがブラウザに描画されます。
let test = new SceneInit(45);
test.initScene();
test.animate();
let geometry = new THREE.BoxBufferGeometry(200, 200, 200);
let material = new THREE.MeshBasicMaterial();
let mesh = new THREE.Mesh(geometry, material);
test.scene.add(mesh);
console.log(test.scene.children); //returns 3 objects (ambientLight, spotLight, mesh)
あなたのカメラを_lookAt_正しい位置にしてみましたか?現在、あなたはz軸にそれを移動しています、そして、私はそれがz軸の下の空隙をさらに見ているかもしれないと思います。 'test.camera.lookAt(mesh.position)'または 'test.camera.lookAt(test.scene.position)'を試してください。しかし、私が時間をかけて学んだことは、これが本当にあなたがこれをどのように使うのかということではないということです。レンダラなどをラップすることで、柔軟性を失うことになります。このコードはこのように使用されることは意図されておらず、グローバル宣言(すべてのレンダラーがメモリを使用している場合)のほうが簡単です。 – somethinghere
答えをありがとうございます。 私がクラスに入れている理由は、さまざまなチャートを表す複数のjavascriptファイルで構成される小さなライブラリを作成するためです。このアプローチでは、このコードを再利用可能にすることができます。 – Bajro
クリーナーコード!==コードを改善! (私はこれが主な理由は、このようなものがintesiveなメモリがあるからです。レンダラーが2つあるよりもレンダラーが優れています。シーンを使用してそれらを分離することができます...しかし、次にバニラthreeJSを意図どおりに使用します)。あなたの問題に関しては、まずレンダリングがあるかどうかチェックします。あなたのメインシーンに巨大なワイヤフレーム球を追加し、それが現れるかどうかを確認するだけです。その後、別の色のキューブを別の方向に配置して、どのように見ているのかを見つけてください...それは時間がかかりますが、それはあなたがそれを理解するのに役立ちます。 – somethinghere