Root
Root

Reputation: 132

Running basic three.js

I've downloaded the three.js from it's official site and I'm try to run very basic file, I'm getting weird error but when I replace the three.js file import with CDN it starts to work. Please help me in starting the file from local.

<html>
    <head>
        <title>1 - First Scene</title>
        <link rel = "stylesheet" href = "Style.css">
<!--        <script src = "../three.js-master/src/Three.js"></script>--> <!-- This doesn't work, I get errors -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js"></script> <!-- This works -->
    </head>
    <body>
    </body> 
</html>

<script >
    let scene, camera, renderer;
    
    // set up the environment - 
    // initiallize scene, camera, objects and renderer
    let init = function() {
        // create the scene
        scene = new THREE.Scene();
        scene.background = new THREE.Color(0xababab);
        
        // create an locate the camera
        
        camera = new THREE.PerspectiveCamera(30, 
                        window.innerWidth / window.innerHeight, 
                        1, 1000);
        camera.position.z = 5;
        
        
        // create the renderer   
        renderer = new THREE.WebGLRenderer();   
        renderer.setSize(window.innerWidth, window.innerHeight);
        
        document.body.appendChild(renderer.domElement);
        
    };
  
    
    // main animation loop - calls 50-60 in a second.
    let mainLoop = function() {
        console.log("Hello");
        renderer.render(scene, camera);
        requestAnimationFrame(mainLoop);
    };
    
    ///////////////////////////////////////////////
    init();
    mainLoop();
</script>

Error screenshot : enter image description here

Upvotes: 3

Views: 837

Answers (1)

Chris Kao
Chris Kao

Reputation: 503

Reason

file:// won't work because you're using module which is ES6 standard.

See here:

Access to Script at ' from origin 'null' has been blocked by CORS policy


Solution

Host a local server and access this HTML with http://localhost URL.

I recommend use http-server

Simply install it with

npm install -g http-server

Assume your folder looks like this:

|- root-path
  |- three.js-master
  |- running-basic-threejs
    |- index.html

And add the type="module" to your script

<script type="module">
    import * as THREE from '../three.js-master/src/Three.js'
    // ...
</script>

Then run http-server in the root-path

cd root-path
http-server .

By default, http-server binds to port 8080. So now you can access your site on http://localhost:8080/running-basic-threejs

Upvotes: 3

Related Questions