In THREE.js, creating a line between two specific mouse click points on a canvas

In this scenario, I aim to showcase the distance between two mouse click locations on the canvas. While I have achieved this functionality, my struggle lies in creating a line connecting these points.

I kindly request suggestions on what steps I should take to address this issue.

var container, camera, scene, renderer, mesh,
        objects = [],
        tempx=0,
        tempy=0,
        count = 0,
        distance = 0,
        CANVAS_WIDTH = 1100,
        CANVAS_HEIGHT = 500;
    
    // Additional information section
    var info = document.createElement('div');
    info.style.position = 'absolute';
    info.style.top = '30px';
    info.style.width = '100%';
    info.style.textAlign = 'center';
    info.style.color = '#f00';
    info.style.backgroundColor = 'transparent';
    info.style.zIndex = '1';
    info.style.fontFamily = 'Monospace';
    info.innerHTML = 'x is: ' + mouse;
    info.innerHTML = 'distance between the present mouse clicks is : ' + distance;
    info.style.userSelect = "none";
    info.style.webkitUserSelect = "none";
    info.style.MozUserSelect = "none";
    document.body.appendChild(info);
    
    container = document.getElementById('canvas');
    document.body.appendChild(container);
    
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(CANVAS_WIDTH, CANVAS_HEIGHT);
    container.appendChild(renderer.domElement);
    
    scene = new THREE.Scene();
    
    camera = new THREE.PerspectiveCamera(45, CANVAS_WIDTH / CANVAS_HEIGHT, 1, 1000);
    camera.position.y = 150;
    camera.position.z = 500;
    camera.lookAt(scene.position);
    scene.add(camera);
    
    scene.add(new THREE.AmbientLight(0x222222));
    mesh = new THREE.Mesh(
        new THREE.BoxGeometry(500, 500, 500, 1, 1, 1),
        new THREE.MeshPhongMaterial({ color: 0X000000 })
    );
    scene.add(mesh);
    objects.push(mesh);
    
    // Intersection calculation
    var raycaster = new THREE.Raycaster();
    var mouse = new THREE.Vector2();
    var clickCount = 0;
    var startPoint = new THREE.Vector3(0, 0, 0);
    var endPoint = new THREE.Vector3(0, 0, 0);
    
    // Mouse listener
    document.addEventListener('click', function (event) {
        clickCount += 1;
        switch (clickCount){
            case 1:
            case 3:
                clickCount = 1;
                startPoint = new THREE.Vector3(
                    ((event.clientX - renderer.domElement.offsetLeft) / renderer.domElement.width) * 2 - 1,
                    -((event.clientY - renderer.domElement.offsetTop) / renderer.domElement.height) * 2 + 1,
                    event.clientZ
                );
                console.log(startPoint.x,
                    startPoint.y,
                    startPoint.z);
                info.innerHTML = "";
                break;
            case 2:
                endPoint = new THREE.Vector3(
                    ((event.clientX - renderer.domElement.offsetLeft) / renderer.domElement.width) * 2 - 1,
                    -((event.clientY - renderer.domElement.offsetTop) / renderer.domElement.height) * 2 + 1,
                    event.clientZ
                );
                console.log(endPoint.x,
                    endPoint.y,
                    endPoint.z);
                
                distance = Math.sqrt(((mouse.x - tempx) * (mouse.x - tempx)) + ((mouse.y - tempy) * (mouse.y - tempy)));
                
                info.innerHTML ='x is:' + mouse.x;
                info.innerHTML = 'y is:' + mouse.y;
                info.innerHTML = 'distance between chosen mouse clicks is :' + distance;
                tempx = mouse.x;
                tempy = mouse.y;
                break;
            default:
                clickCount = 0;
                startPoint = new THREE.Vector3(0, 0, 0);
                endPoint = new THREE.Vector3(0, 0, 0);      
        }
    }, false);

Answer №1

This illustration provides a valuable clue on how to connect points with lines:

const material = new THREE.LineBasicMaterial( { color: 0x00ff00 } );

const dots = [];
dots.push( new THREE.Vector3( - 5, 0, 0 ) );
dots.push( new THREE.Vector3( 0, 5, 0 ) );
dots.push( new THREE.Vector3( 5, 0, 0 ) );

const structure = new THREE.BufferGeometry().setFromPoints( dots );

const linkage = new THREE.Line( structure, material );

container.add( linkage );

You can find this demonstration at threejs.org in the documentation section related to drawing lines. I suggest exploring that guide as it offers clear explanations and numerous examples!

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

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Encountering an issue with Spring and AngularJS, as I am receiving an HTTP Status 404 error message

I'm encountering an HTTP Status 404 error within my controller. Server code @RequestMapping(value="/showMsg/", method=RequestMethod.GET,produces= { "application/json" })' public ResponseBody String show(){ HashMap hash = new HashMap(); ...

Why did the bootstrap installation in my project fail?

Previously, everything on my website was functioning correctly. However, upon launching it now, I noticed that the carousel, buttons, and other elements are broken. It seems like there might be an issue with the Bootstrap CDN as the buttons and sliders are ...

Is it possible to create a Nuxt.js static website that incorporates a dynamic single-page application built with Vue.js

Currently researching Static Site Generators for a client project, I discovered Vue.js and Nuxt.js, which appear promising. Given the choice between Vue.js and React, I lean towards Vue at the moment. The client's website consists of 120 pages with s ...

Managing the hovering of a mouse over an image within an isometric grid displayed on a

I have implemented an isometric grid in HTML canvas. My goal is to handle mouse hover events on the buildings within the grid. Some buildings will vary in heights. In the image below, you can see that when hovering over a tile, the highlighted area shif ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

"Put Phonegap on hold for a bit and disable landscape mode

I am currently using Phonegap to develop an Android game. My project includes a lobby feature where players can search for opponents and engage in chat with other players. Once a player has found their opponent, they can commence playing the game together ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Unable to modify a record using the 'findById' method and save() function while utilizing promises

I am in the process of developing a cinema application using Node.js and MongoDB with Mongoose. One specific requirement I have is to update the 'Show' model when a user places an order. The task involves adding the latest seats that were ordere ...

working with a list of Python objects in a JavaScript environment

Currently, I am building a web application using Flask and Python. In my Python code, I have a class that can be parsed as JSON. class uItem: itemCount = 0 def __init__(self, id, name): self.id = id self.name = name I am trying to acce ...

Having trouble implementing the center edge effect in this CSS design

Looking for help with CSS to center the edges of a family tree design. Has anyone experience in working on styling family trees? *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .tree { ...

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

What is the best way to utilize webpack solely for bundling without using webpack dev server?

Can anyone help me figure out how to use a single server, node.js, to display a react page without using webpack dev server but still bundle code using webpack? Here are the code folders I have: LINK I am working on the server side with node.js/express an ...

Transform CSV data into JSON format to generate an empty JSON file

I've been attempting to convert a CSV file to JSON using the convert-csv-to-json package from npm. Although I can successfully retrieve the CSV file from the specified URL and create a 'data.csv' file, the resulting JSON file is only an empt ...

Google Drive API generates new blank file named 'Untitled' when used with certain browser versions

Trying to utilize the 'browser' version of the Google Drive API, which seems to mostly adhere to Nodejs syntax. However, there are limited examples available beyond the basic hello world example for the browser. Currently, the goal is to create ...

Removing data using axios in a React project

I'm currently working on a small app using the Json server package to help me keep track of movies I want to watch in my free time. I am looking to learn React and Axios, so I decided to build this app with these technologies. The concept is simple - ...

Is there a way to use jQuery to gather checkboxes and add the selected ones to an array?

How can I efficiently collect values of checked checkboxes with a specific classname and store them in an array? Here is the current approach: var a = new Array(); $('.categoriesCb').each(function(i, item) { if ($(item).prop('checked&apos ...

Ways to delete a class if it currently exists?

Is there a way to manage multiple toggle classes within a single div? It can be frustrating when clicking the maximize or close button triggers the minimize function as well. How can this situation be addressed? Is there a way to manage multiple toggle cl ...