我一直试图通过用于WebGL的Three.js库来实现一个简单的旋转3D立方体。
与大量的教程相比,我似乎无法识别代码中的任何错误,但我看到的只是一个没有几何形状的黑屏。
//Define window size
var width = window.innerWidth;
var height = window.innerHeight;
//smoothened edges for the renderer defined
var renderer = new THREE.WebGLRenderer({antialias:true});
//renderer size
renderer.setSize(width,height);
//renderer is appended to the html document
document.body.appendChild(renderer.domElement);
var scene = new THREE.Scene;
//Add Cube - width, height, depth
var cubeGeom = new THREE.CubeGeometry(100,100,100);
var cubeMaterial = new THREE.MeshLambertMaterial({color:0x1ec876});
var cube = new THREE.Mesh(cubeGeom,cubeMaterial);
//Rotate cube 45 degrees
cube.rotation.y=Math.PI*45/180;
//Add cube to scene
scene.add(cube);
//Add Camera - FOV, Ratio, Close, Far
var camera = new THREE.PerspectiveCamera(45,width/height,0.1,10000);
//Position camera
camera.position.y = 160;
//Higher the z value, the closer to the camera/user
camera.position.z = 400;
//Camera pointed towards cube
camera.lookAt(cube.position);
//Add camera to scene
scene.add(camera);
//Define skyBox
var skyBoxGeom = new THREE.CubeGeometry(10000, 10000, 10000);
var skyBoxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
var skyBox = new THREE.Mesh(skyBoxGeom,skyBoxMaterial);
scene.add(skyBox);
//Point Light
var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0,300,200);
scene.add(pointLight);
//Render scene
function render() {
render.render(scene,camera);
var clock = new THREE.Clock;
//rotate cube clockwise - subtract time passed from rotation
cube.rotation.y -=clock.getDelta();
requestAnimationFrame(render);
}
//Call render function
render();

canvas {
position: fixed;
top:0;
left:0;
}

<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
&#13;
P.S。我通过在此处找到的Google Developer链接上找到的CDN链接到Three.js:https://developers.google.com/speed/libraries/
非常感谢任何帮助。
非常感谢 汤姆
答案 0 :(得分:0)
第55行的JS代码中有一个小错字:
render.render(scene,camera);
应该是:
renderer.render(scene,camera);
下次我强烈建议打开浏览器的控制台时,错误已经记录下来,因此修复错误非常简单。
除此之外,你的代码工作正常。立方体旋转,虽然它非常慢。您可能需要调整第60行以使其旋转得更快(例如,将值乘以100)。