简体   繁体   English

Three.js的第一个例子不起作用

[英]First example of Three.js doesn't work

I'm about to learn three.js . 我即将学习three.js I've downloaded the library from github: three.js 我从github: three.js下载了这个library

I tried to run the first example of three.js in the link above. 我试图在上面的链接中运行three.js的第一个例子。 The weird problem is, it's working in jsFiddle but it not working in my computer. 奇怪的问题是,它在jsFiddle中工作,但它在我的计算机中不起作用。

I've this error in console: 我在控制台中出现此错误:

TypeError: document.body is null
[Break On This Error]   
document.body.appendChild( renderer.domElement );


jsFiddle Live Working Demo jsFiddle Live Working Demo

And here is my code exactly copied from link above: 这里是我的代码从上面的链接完全复制:

And yes the three.js included in the page. 是的,页面中包含了three.js。

    var camera, scene, renderer;
    var geometry, material, mesh;

    init();
    animate();

    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 );

    }

Your code is running before the browser has parsed the HTML document and built the DOM. 在浏览器解析HTML文档并构建DOM之前,您的代码正在运行。 That's why document.body is undefined. 这就是为什么document.body未定义的原因。

Use a "load" event handler: 使用“load”事件处理程序:

window.onload = function() {
  // all that code here
};

Your jsfiddle version worked because that site does that for you; 你的jsfiddle版本有效,因为该网站为你做了这个; it's what the top selection thing is for on the left-hand side control panel. 它是左侧控制面板上最佳选择的东西。

Oh, also, you have to be careful when copying code from jsfiddle. 哦,还有,从jsfiddle复制代码时要小心。 Unless they've fixed it with the recent facelift, it's really easy to pick up weird hidden characters when you copy/paste, causing mysterious JavaScript errors. 除非他们使用最近的整容修复它,否则在复制/粘贴时很容易找到奇怪的隐藏字符,从而导致神秘的JavaScript错误。

Just write your code inside onload . 只需在onload编写代码即可。 it works fine. 它工作正常。

window.onload = function() { // your code }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM