single-page-threejs-html-loading-3d-file

single-page-threejs-html-loading-3d-file

Using a simple boilerplate code can be a great way to quickly start a new or experimental Three.js project, and it can help you get up and running with your project faster and more efficiently.

Using a boilerplate code is a great way to quickly start a new or experimental project. With a boilerplate code, you can avoid having to write the basic setup code from scratch, which can be time-consuming and error-prone.

Instead, you can use a boilerplate code as a starting point and build upon it to create your project. A boilerplate code for Three.js typically includes the basic components required to create a Three.js scene, such as a renderer, a camera, and a scene. It may also include a basic object, such as a cube or sphere, that you can modify or replace with your own custom 3D models.

A boilerplate code using HTML and JavaScript can be started with a single HTML file, making it convenient to quickly start a new Three.js project while keeping the file structure simple. This type of boilerplate code includes all the Three.js and HTML code within a single HTML file. This allows you to create a Three.js scene without the need for additional JavaScript or CSS files.

By starting with a single HTML file as a boilerplate code, you can reduce the amount of organization and maintenance considerations required for the code. You can also test and experiment with the basic features of Three.js while keeping the initial version of the project simple.

However, if you need to load external files, they must be provided through a server due to security issues. In this case, the single HTML file only contains Three.js and HTML code, and all external files are loaded from the server.

1. Startup of Three.js

Three.js is a powerful JavaScript library for creating 3D animations and graphics on the web. If you’re new to Three.js and want to quickly get started with creating a simple example, here is a simple boilerplate code that you can use.

First, create a new HTML file and give it a name of your choice, for example, threejs-boilerplate.html. Then, add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three.js Boilerplate</title>
    <style>
        body { margin: 0; }
        canvas { display: block; }
    </style>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
    <script>
        // Create the scene
        const scene = new THREE.Scene();
        scene.background = new THREE.Color( 0xaaaaff );
        
        // Create the light
        const light = new THREE.DirectionalLight( 0xffffff );
        light.position.set( 0, 0.5, 1 );
        scene.add( light );

        // Create the camera
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        
        // Create the renderer
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);
        
        // Create a cube
        const geometry = new THREE.BoxGeometry();
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        const cube = new THREE.Mesh(geometry, material);
        scene.add(cube);
        
        // Position the camera
        camera.position.z = 5;
        
        // Animate the cube
        function animate() {
            requestAnimationFrame(animate);
            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;
            renderer.render(scene, camera);
        }
        animate();
    </script>
</body>
</html>

Here are the brief explanation of code.

This code start by defining an HTML document with a head and body section.

  1. In the head section, set the document’s character set, give it a title and define some simple CSS styles for the body and canvas elements.
  2. In the body section, add the Three.js library by including a script tag with a link to the library’s CDN. We also create a script tag to write our Three.js code in.
  3. Create a new scene object with THREE.Scene().
  4. Create a camera object with THREE.PerspectiveCamera(). The first argument sets the camera’s field of view (in degrees), the second argument sets the camera’s aspect ratio, the third argument sets the camera’s near clipping plane, and the fourth argument sets the camera’s far clipping plane.
  5. Create a renderer object with THREE.WebGLRenderer(). We set its size to match the window’s inner size and append its domElement to the body.
  6. Create a cube with THREE.BoxGeometry() and a green MeshBasicMaterial() with THREE.MeshBasicMaterial(). We then create a Mesh object by combining the cube geometry and material with THREE.Mesh(). Finally, we add the Mesh object to the scene.
  7. Position the camera by setting its position.z property to 5.
  8. Define an animate() function that will be called by requestAnimationFrame() and will rotate the cube and render the scene.
  9. Start the animation loop by calling animate().

Now, save your HTML file and open it in your web browser.

2. Opening local html file in a web browser 

The above example can be loaded in a web browser by simply opening the HTML file from your local file system.

open local html file in a browser

Since the code does not load any external files such as 3D models or textures, the browser does not need to make any additional requests to the server to load these resources. The entire code is self-contained within the HTML file, and as a result, the code can be run directly from the file system without needing to be served by a web server.

However, it’s important to keep in mind that when loading external files such as 3D models or textures, the Same-Origin Policy security restriction applies. This means that the web browser may block the loading of external resources if they are not hosted on the same domain as the HTML file.

To avoid this security restriction, it is recommended to serve your HTML file and any external resources from a web server, even if they are located on the same local file system. This ensures that the browser will not block the loading of external resources and that your code will work consistently across different web browsers and platforms.

3. Loading external files in three.js html file 

When you need to load separate 3D model or texture files, you will need to use additional Three.js classes and methods to load them into your scene.

To load a 3D model, you can use the THREE.GLTFLoader class. This loader can handle various 3D model formats, including .glb and .gltf. Here is an example code that loads a 3D model and adds it to the scene:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three.js Boilerplate</title>
    <style>
        body { margin: 0; }
        canvas { display: block; }
    </style>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/three@0.138.0/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.138.0/examples/js/loaders/GLTFLoader.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.138.0/examples/js/loaders/RGBELoader.js"></script>
    <script>
        // Create the scene
        const scene = new THREE.Scene();
        scene.background = new THREE.Color( 0x00aaff );
        
        const light = new THREE.DirectionalLight( 0xffffff );
        light.position.set( 0, 0.5, 1 );
        scene.add( light );
        
        // Create the camera
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        
        // Create the renderer
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);
        
        // Load the 3D model
        const loader = new THREE.GLTFLoader();
        //const modelUrl = "./DamagedHelmet.glb";
 
        // If server of external asset allows CORS, it can be loaded from a local file.
        const modelUrl = "https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/DamagedHelmet/glTF-Binary/DamagedHelmet.glb";
        
        let model = null;
        loader.load(modelUrl, function (gltf) {
            scene.add(gltf.scene);
            model = gltf.scene;
 
            const bbox = new THREE.Box3().setFromObject(scene);            
            const bsize = bbox.getSize(new THREE.Vector3());
            const radius = bsize.length();
            // Position the camera to view entire model.
            camera.position.z = radius;
        });        
        
        // create environment map for background and reflection 
        const envmap = new THREE.RGBELoader()
            .setPath('https://threejs.org/examples/textures/equirectangular/')
            .load('royal_esplanade_1k.hdr', function ( texture ) {
                texture.mapping = THREE.EquirectangularReflectionMapping;
 
                scene.background = texture;
                scene.environment = texture;
            });
                    
        // Animate the scene
        function animate() {
            requestAnimationFrame(animate);
 
            if (model) {
                model.rotation.y += 0.01;
            }
 
            renderer.render(scene, camera);
        }
        animate();
    </script>
</body>
</html>

This code uses the THREE.GLTFLoader class to load the model file. When the loading is complete, the loaded 3D model is added to the scene. If an error occurs during loading, an error message is output to the console.

The 3D model and texture files can be downloaded from the following path:

https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/DamagedHelmet/glTF-Binary/DamagedHelmet.glb

https://github.com/mrdoob/three.js/blob/r138/examples/textures/equirectangular/royal_esplanade_1k.hdr

If the second example is executed correctly, you should see a screen with a 3D model that rotates automatically, as shown in the image below. Since the second example is executed on a web server, if you name the example file index.html, it will open directly to the URL localhost:8000.

4. Simple Web Server

If you want to load external files such as 3D models or textures in your HTML file, you need to serve your HTML file from a web server.When you open an HTML file from your local file system by double-clicking on it or using the file protocol (file://) in your web browser, the web browser’s security policies restrict certain types of access to local resources, including loading external files. This is known as the “Same Origin Policy” and is a security measure to prevent malicious scripts from accessing sensitive information on a user’s computer.

To serve your HTML file from a web server, you can install a local web server on your computer or use a hosting service to host your website online. There are many options available, both free and paid, depending on your needs.

For example, you can download simple standalone command line web server here:

TinyWeb

# run server with www-root-directory and port-number
tiny.exe www-root-directory 8000

Also, Python has a simple, fast, light HTTP server module:

# execute python module
python -m SimpleHTTPServer
# or the Python 3 equivalent
python3 -m http.server

Node.js has a HTTP server module too:

# install module system-wide
npm install http-server -g

# run server with www-root-directory and port-number
http-server www-root-directory -p 8000

If you are using a local web server, your URL might be something like http://localhost:8000/threejs-boilerplate.html. This will allow you to load external files from your server and use them in your Three.js code.

Conclusion

Using a boilerplate code can save you a lot of time and effort, allowing you to focus on the creative aspects of your project. It also helps ensure that your project is built on a solid foundation, with a well-organized code structure and best practices in mind.

However, it’s important to keep in mind that a boilerplate code is just a starting point. As you develop your project, you may need to modify or customize the code to fit your specific needs. You may also need to add additional components, such as lighting, materials, or textures, to create a more realistic and immersive scene.

Overall, using a simple boilerplate code can be a great way to quickly start a new or experimental Three.js project, and it can help you get up and running with your project faster and more efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *