我是webGL和three.js的新手,我刚刚从JSFiddle中选了一个例子,
http://jsfiddle.net/BlackSRC/XWCRM/1/
但是当我测试它时,我什么都没得到, 守则如下:
<!DOCTYPE html>
<html>
<head>
<title>ThreeJS</title>
</head>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/mrdoob-three.js-2524525/build/three.js"></script>
<script>
function onLoadComplete() {
init();
animate();
}
var camera, scene, renderer;
var geometry, material, mesh;
function init() {
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1000;
scene = new THREE.Scene();
geometry = new THREE.CubeGeometry(200, 200, 200);
material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function animate() {
// note: three.js includes requestAnimationFrame shim
requestAnimationFrame(animate);
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render(scene, camera);
}
</script>
<body onload="onLoadComplete();">
我错过了什么吗? 谢谢你的帮助!
答案 0 :(得分:0)
您的代码没有任何问题,但您使用的是本地js文件。所以它在身体dom渲染之前运行js代码运行,所以当调用document.body.appendChild(renderer.domElement);
时会导致错误:
test.html:45未捕获的TypeError:无法读取属性&quot; appendChild&#39;的 空(...)
并生成空白页面。 但是,当我测试远程js文件不存储在本地时,它运行良好。因此,要避免此问题,请在dom之后加载js。
下面是代码,我只是js代码之前的正文,并使用在线js文件。这里放js代码后的body也可以工作,因为js从远程加载,当js运行时,正文已经渲染。
<!DOCTYPE html>
<html>
<head>
<title>ThreeJS</title>
<body onload="onLoadComplete();">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/renderers/CanvasRenderer.js"></script>
<script src="https://threejs.org/examples/js/renderers/Projector.js"></script>
<script>
function onLoadComplete() {
init();
animate();
}
var camera, scene, renderer;
var geometry, material, mesh;
function init() {
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1000;
scene = new THREE.Scene();
geometry = new THREE.CubeGeometry(200, 200, 200);
material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function animate() {
// note: three.js includes requestAnimationFrame shim
requestAnimationFrame(animate);
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render(scene, camera);
}
</script>
</html>
&#13;