What are the steps to implement THREE.MeshLine in my JavaScript project?

While exploring ways to create a line using three.js with a modified width, I stumbled upon this article suggesting the usage of a THREE.MeshLine class available here. However, when I attempted to follow the documentation to implement it in my script, I encountered an error:

require.js:5 Uncaught Error: Module name "three" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
    at makeError (require.js:5)
    at Object.o [as require] (require.js:5)
    at requirejs (require.js:5)
    at test_line.html:13

Below are the lines of code that I added to my script:

<html>
    <head>
        <script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r119/three.min.js"></script>
        <script src="https://raw.githubusercontent.com/spite/THREE.MeshLine/master/src/THREE.MeshLine.js"></script>
        <title>Test</title>
    </head>
    <body>  
        <script>
            var THREE = require( 'three' );
            var MeshLine = require( 'three.meshline' );
            ...

Am I missing something? (Note: I am new to JavaScript)

I also attempted to follow the recommendations HERE, but encountered an error stating container is not defined as soon as I added type="module" in the script section.

Below is a complete, self-contained, static, straightforward example of a single line in a browser window. I would appreciate if the response includes a fixed, complete, self-contained, static, straightforward example of the code!

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r119/three.min.js"></script>
        <title>Test</title>
    </head>
    <body>
        
        <script>
            container = document.createElement('div');
            document.body.appendChild(container);
            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
            camera.position.set(0, 0, 150);
            scene = new THREE.Scene();
            scene.add(camera);
            renderer = new THREE.WebGLRenderer({
                clearAlpha: 1
            });
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setClearColor(0xcaffee, 1);
            document.body.appendChild(renderer.domElement);
            
            var material = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 10000000 } );
            var points = [];
            points.push( new THREE.Vector3(-50, 0, 0 ) );
            points.push( new THREE.Vector3( 50, 0, 0 ) );
            var geometry = new THREE.BufferGeometry().setFromPoints( points );
            var line = new THREE.Line( geometry, material );
            scene.add( line );
            renderer.render( scene, camera );
            
            animate();
            function animate() {
                requestAnimationFrame(animate);
                renderer.render(scene, camera);
            }
            
        </script>
    </body>
</html>

Answer №1

Edit 2: After receiving feedback from @user2589273, it was noted that this answer is no longer applicable as the original repository (https://github.com/spite/THREE.MeshLine) has integrated the fork mentioned below into the main repository. However, I will keep the answer here for historical purposes.

The Meshline repository provided in your link is no longer actively maintained and may not be compatible with the latest versions of three.js. I recommend using the updated fork that I am currently using: https://github.com/ryanking1809/threejs-meshline

To make it work, simply replace the link in your question with the following:

https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="03776b71666669702e6e66706b6f6a6d6643312d332d3232">[email protected]</a>/src/index.js

Edit: A complete working example is provided below:

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r119/three.min.js"></script>
        <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a3bfa5b2b2bda4fabab2a4bfbbbeb9b297e5f9e7f9e6e6">[email protected]</a>/src/index.js"></script>
        <title>Test</title>
    </head>
    <body>

        <script>
            container = document.createElement('div');
            document.body.appendChild(container);
            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
            camera.position.set(0, 0, 150);
            scene = new THREE.Scene();
            scene.add(camera);
            renderer = new THREE.WebGLRenderer({
                clearAlpha: 1
            });
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setClearColor(0xcaffee, 1);
            document.body.appendChild(renderer.domElement);




            let points = [];
            points.push( new THREE.Vector3(-50, 0, 0 ) );
            points.push( new THREE.Vector3( 50, 0, 0 ) );
            const line = new MeshLine();
            line.setVertices(points);
            const material = new MeshLineMaterial();

            const mesh = new THREE.Mesh( line, material );
            scene.add( mesh );
            renderer.render( scene, camera );

            animate();
            function animate() {
                requestAnimationFrame(animate);
                renderer.render(scene, camera);
            }

        </script>
    </body>
</html>

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

Checkbox Hierarchy: Children marked as either Checked or Unchecked based on parent selection

Hello, I have a form that contains nested checkboxes on three levels. Using jQuery, I am trying to check/uncheck all the children when I check a parent level... and if any of the children are unchecked, uncheck the parent as well. I have attempted this m ...

Converting Database Information to JSON Format for Mobile Authentication Form

Currently, I am working on a Mobile App project using Phonegap that requires users to log in before retrieving JSON data. This PHP page is responsible for connecting to the mobile site and fetching the necessary information. <?php $con = mysqli_connec ...

having difficulty applying a border to the popup modal

Currently, I am utilizing a Popup modal component provided by the reactjs-popup library. export default () => ( <Popup trigger={<button className="button"> Guide </button>} modal nested > {(close: any) =&g ...

Can you explain the function of "app.router" in the context of Express.js?

When looking at the default app.js file generated by express.js, I came across the following line: ... app.use(app.router); ... This particular line of code has left me perplexed for a couple of reasons. First, upon consulting the express api documentati ...

Improving mongo information using angularjs

Have an Angular and MongoDB application. This is a part of my API where I have POST and PUT requests. The POST request works fine, but when I send a PUT request, I get an error "Cannot set property 'typelocal' of undefined". However, the PUT requ ...

Utilize Node.js and Socket.IO to download a PNG image in a web browser

Looking for assistance in saving an image from Flash to a server using node.js. Below is my code snippet: var pngEncoder:PNGEncoder = new PNGEncoder(); var pngStream:ByteArray = PNGEncoder.encode(bmd); socket.send(pngStream,"image"); Above is the Flash c ...

Issues with previewing PDF files in AngularJS

I am trying to display a PDF preview on my website using the following code: var $scope; angular.module('miniapp', ['phonecatFilters', 'ngSanitize']); function Ctrl($scope) { $scope.test = 'Example from: '; ...

Electron / Atom Shell unable to locate specified module

I am completely new to npm, node, and Electron. Here is the structure of my folder: -package.json -index.html -main.js -js/myStuff.js -node_modules In the file myStuff.js, I have a line that says var chokidar = require('chokidar'); but it keep ...

When handling a document click event in Typescript, an error may occur where it cannot read

Just starting out with Typescript and diving into Angular, I am currently in the process of converting my project to the Angular system. However, I've hit a roadblock. I need to figure out how to close the dropdown content when the user clicks anywher ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

Enhancing Rails: Tailoring the flash message to suit individual needs

I am embarking on my journey with ruby on rails and could use some guidance with the following scenario. In the application.html.erb file, flash messages are configured to fade out after a few seconds by default. <div id="message" class="modal alert a ...

Having trouble rendering JSON encoded data in a JqPlot Chart within a PHP script

I've spent the past few days scouring through Stack Overflow and various other websites, but I haven't been able to find a solution to my specific issue. Even the book 'Create Web Charts with JqPlot' by Fabio Nelli didn't provide t ...

What is the most efficient way to transfer a value from the main application file to a router file using the express framework

Currently, I am developing an Express application with multiple routes. To ensure modularity, each route will have its own file stored in a dedicated routes folder. One challenge I encountered is sharing a common value across all routes. Specifically, I n ...

Ways to determine whether a DOM textnode is a hyperlink

Is there a more foolproof method for determining if a DOM textnode represents a hyperlink? The code snippet below currently only checks if the node is directly enclosed in an anchor tag, which may not be sufficient if the <a> element is higher up i ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...

Having trouble with res.render() when making an axios request?

I am encountering an issue with my axios requests. I have two requests set up: one to retrieve data from the API and another to send this data to a view route. const response = await axios({ method: 'POST', url: 'http:// ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...