Executing a fundamental three.js program

After downloading three.js from the official site, I encountered a strange error while trying to run a basic file. However, when I replaced the local import of the three.js file with a CDN, it started working properly. Can someone assist me in getting the file to run locally?

<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 - 
    // initialize scene, camera, objects and renderer
    let init = function() {
        // create the scene
        scene = new THREE.Scene();
        scene.background = new THREE.Color(0xababab);
        
        // create and position 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 times in a second.
    let mainLoop = function() {
        console.log("Hello");
        renderer.render(scene, camera);
        requestAnimationFrame(mainLoop);
    };
    
    ///////////////////////////////////////////////
    init();
    mainLoop();
</script>

Error screenshot : https://i.sstatic.net/AObfT.png

Answer №1

Explanation

file:// cannot be used due to the module being an ES6 standard.

For more information, refer to:

Error: Access to Script blocked by CORS policy


Resolution

To resolve this issue, set up a local server and access the HTML file using the http://localhost URL.

I suggest utilizing http-server

Simply install it by running

npm install -g http-server

If your directory structure is as follows:

|- main-folder
  |- three.js-master
  |- running-basic-threejs
    |- index.html

Add type="module" to your script tag like so:

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

Then run http-server in the main-folder

cd main-folder
http-server .

The default port for http-server is 8080. You can now access your site at

http://localhost:8080/running-basic-threejs

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The rotation function of a THREE.js object seems to be malfunctioning

Currently, I am facing an issue with a Blender object that I have successfully displayed on my web page using THREE.js. However, for some reason the object is not rotating when my loop function is called. In my approach to working with JavaScript, I am tr ...

Utilize the result of an Ajax request to populate the data section of a Flot chart with an

I am having difficulty integrating data retrieved from my database into a Flot chart within the success function of an ajax call. The data returned from the server is in the following format: [[5,29],[6,57],[7,31]] My goal is to use this data in the "dat ...

Angular - Strategies for Handling Observables within a Component

I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...

Having trouble with jQuery toggle fade: Unable to make the div fade in/out when toggling

Is there a way to modify the functionality of my black button so that when clicked, the red div fades out while the blue div fades in? Right now, clicking the button switches between the two divs without any fading effect. Fiddle: http://jsfiddle.net/ddac ...

Creating a three.js Geometry directly from a JSON object without relying on JSONLoader

In my current project, I am working on a scene where I need to import objects from JSON files exported from Blender and then add them to the scene. Because this project will be a Cordova app, I am unable to use JSONLoader or any XHR resource. Although I h ...

Setting up a nodejs application on a web server

As a newcomer to NodeJS, I am currently learning how to create a sample app using this technology. I have successfully tested it on my localhost, but now I am facing issues when trying to host it on a public server. var http = require('http'); ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Pause and Persist

Can someone help me clarify a code issue I'm facing? I have a piece of code that checks an array for overlapping values based on different criteria. This code specifically deals with rows and columns in a Google Sheet using GAS. Here's what I cur ...

Instructions for creating a directional route on a map using highcharts

I am currently working on implementing highcharts maps with flight routes, similar to the visualization shown in this Highchart-maps with flight routes example. My goal is to display the routes in a way that resembles the output illustrated in this expecte ...

Is there a way to make a link clickable but also prevent another link from being activated when clicked?

Have you ever utilized #link to navigate to a specific section on a webpage? You can also incorporate animate and scrollTop() to ensure a smooth scroll. However, when the #link (Hash link) is situated in the navigation menu, it must be structured as exampl ...

Looking to display information in a column-by-column format using ng-grid within Angular JS

The data I have is structured like this: $scope.myStudentData = {"Moroni":{"id":"1","grade":"A"},"Tiancum":{"id":"2","grade":"B"}} However, the grid requires a different format: $scope.myGridOptions = [{"details":"id", "Moroni":"1", "Tiancum":"2"},{"det ...

Using PHP and jQuery to showcase files found within a directory

My goal is to use a combination of PHP and jQuery to display files stored in a specific directory. I have integrated Datatables to present all the records from a database, some of which have files associated with them. Users can click a link to open a moda ...

Executing a particular function on multiple buttons that have not been initialized yet

I am struggling to make this code work for every button and I haven't been able to find an explanation for the issue. I believe it may be a small detail that I am overlooking. $(document).ready(function() { // delete the selected row from the datab ...

I keep running into a problem that says "Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))". I've been unable to come up with a solution so far

const Header = () => { const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{user}, dispatch] = useStateValue(); const login = async () =>{ const { user: { refreshToken, providerData }, } = await sign ...

Switch the Angular app written in Javascript to Typescript

I am looking to create a pluginable Angular app and came across this tutorial that uses RequireJs for loading scripts in the correct order. Now, I want to convert this project to TypeScript but I am unsure of how to incorporate RequireJs into TypeScript. ...

Changing the story in javascript

I am trying to customize the legend to display the following values: 80+ (or 80%+) 75-80 70-75 65-70 60-65 55-50 <50% While I have organized the list in descending order, I seem to be facing an issue with getting the less than symbol to function corr ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Transmitting information through ajax and fetching it using Request.Form[""]

My struggle lies in passing parameters from a js script to an aspx.cs page. Interestingly, when I exclude the following line: contentType: "application/json; charset=utf-8" from my ajax request, the data received by Request.Form["ORDER"] appears as {%7b% ...

Leverage the power of React by utilizing SVGR to easily integrate SVG files

Wondering if there's a way to bring in an SVG file from my public folder and use it as a React component like this: import { ReactComponent as MySvg } from '/assets/svg/mysvg.svg'; const MyComponent = () => { return ( <div> ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...