How to use mousedown event in Three.js to create line drawings

I've tried multiple approaches to achieve this effect. I'm looking to draw a line on mouse down event, and despite researching various resources, I haven't been able to come up with a solution. Currently, I'm utilizing the RayCaster method of intersectObjects() to obtain the click position. However, I'm unsure of what to do next. I would really appreciate any advice or guidance. Here is a snippet of my code:

event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = -( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;  
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects, true);
console.log(intersects[0].point);

Yesterday, I made some progress with my code. Here are some additional snippets:

var clickCount = 0; // Initial value
clickCount = clickCount + 1;
if (intersects.length > 0) {
    switch (clickCount) {
        case 1:
            var startPoint = intersects[0].point;
            break;
        case 2:
            var endPoint = intersects[0].point;
            break;
    }
}

clickCount = 1;
var geometry = new THREE.Geometry();
material = new THREE.LineBasicMaterial({ color: 0xffffff, linewidth: 2 });
geometry.vertices.push(startPoint);
geometry.vertices.push(endPoint);
line = new THREE.Line(geometry, material);
scene.add(line);

However, the resulting lines are not exactly what I intended. They appear to be rays originating from the vector (0, 0, 0). Please refer to the screenshot here: https://i.sstatic.net/hrsql.png

The red line represents the effect I am aiming to achieve. Can anyone pinpoint the reason for the discrepancy? Your assistance is greatly appreciated.

Answer №1

One effective strategy is to keep track of the first clicked object and then compare it with subsequent clicks. If the clicked object is different from the first one, draw a line connecting them.

var intersected, lineObjects = [],
objects = [];
. . .

Within the event handler:

  if (intersects.length > 0) {
    var found = intersects[0].object;
    if (found != intersected) {
      if (lineObjects.length > 0) {
        var line = lineObj(lineObjects[0].position, found.position);
        scene.add(line);
        lineObjects[0].material.color.setHex(lineObjects[0].userData.oldColor);
        intersected = null;
        lineObjects = [];
      } else {
        found.userData.oldColor = found.material.color.getHex();
        found.material.color.set(0x00FF00);
        intersected = found;
        lineObjects.push(found);
      }
    } else {
      found.material.color.setHex(found.userData.oldColor);
      intersected = null;
      lineObjects = [];
    }
  }

An example of this functionality can be found in this jsfiddle. Refer to the onMouseDown() function for a demonstration of the described process.

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

Discovering the true width of an element using JavaScript

Hey there, I'm currently attempting to determine the exact width of a specific element and display an alert that shows this width. The code I am using is as follows: HTML Element <table cellspacing="1" cellpadding="5" style=";width:975px;border: ...

How can I transfer data from a C# code to a JavaScript file in asp.net?

I am faced with the task of transferring values from a C# class to a JavaScript file. To achieve this, I have generated a string in C# which contains the values of the list as follows: count = 0; JString = "["; for(i=0; i<x; i++) { JString += "{Sou ...

The Chart.js donut chart is not displaying as expected on the HTML page when using

My HTML code is set up to display a donut chart with database records retrieved through a PHP script. The data is successfully fetched and visible in the browser console, but the chart itself is not showing up. How can I resolve this issue? console.lo ...

Merge two distinct JSON objects obtained through an API request using Javascript

Struggling with my currency conversion project, I'm trying to display JSON response results on my website but can't seem to make it work. The code snippet below, .then((response) => { return response.json(); }) .then((jsonRespo ...

Sending information from a parent component to a nested child component in Vue.js

Currently, I am facing a challenge in passing data from a parent component all the way down to a child of the child component. I have tried using props to achieve this as discussed in this helpful thread Vue JS Pass Data From Parent To Child Of Child Of Ch ...

What is the reason for not storing information from MySQL?

Looking to extract data from a website using this JavaScript code. var i = 0 var oldValue = -1 var interval = setInterval(get, 3000); function get(){ var x= $($('.table-body')[1]).find('.h-col-1') if(i!=5){ if(oldValue != x){ old ...

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

How can I take a screenshot from the client side and save it on the server side using PHP?

Currently, I am exploring the possibility of screen capturing at the client side. It appears that the "imagegrabscreen()" function can only capture screens on the server side. After some research, I discovered a new function that allows for screen capture ...

What steps can I take to resolve this issue when encountering an error during npm install?

As a newcomer to programming, I am embarking on the creation of a Discord bot using node and discord.js. My current hurdle involves the installation of a library named canvas, which seems to be causing issues. After developing and testing my application o ...

Optimal row settings for different reports using Material-UI table pagination

Recently, I've been exploring an example involving material-ui's TablePagination. In this scenario, they present a useTable component with the following code snippet: import React, { useState } from 'react' import { Table, TableHead, Ta ...

What could be causing the absence of req.body data in a specific route in my Node JS application?

Hello, I am encountering an issue with my Node JS application: When attempting to authenticate, I am receiving an "undefined" value for "req.body.username" upon sending a POST request to that specific route. This problem seems to only occur on this parti ...

Error message: "Window is not defined in Next.js"

Can anyone help me with this issue I'm experiencing: 'window is not defined' error? useEffect(() => { const handleScroll = () => { if(typeof window !== 'undefined') { // scrolling dete ...

Anticipated the presence of a corresponding <div> within the server's HTML nested in another <div>

I've encountered a troubling error on my website while using Next.js. The error is causing layout issues and upon investigation, it seems that the device detection hook is at fault. Here's the hook in question: const isBrowser = typeof window !== ...

Intercepting the K-pager navigation with a pop-up modal for user confirmation before switching to a different page

Scenario Currently, I have developed a WebApp using kendo, bootstrap, and backbone. One of the key features is a grid that showcases data pulled from a database. This grid has a data source binding with serverPaging enabled. Data Source Configuration al ...

The FBXLoader in Three.js encountered an error while loading a large FBX model

I'm experiencing an issue where Chrome crashes when I try to load a large FBX model (100MB) in three.js, but it doesn't crash with smaller models. Does anyone know how I can resolve this problem? ...

Tips for recognizing the click, such as determining which specific button was pressed

Currently, I am utilizing Angular 6. On the customer list page, there are three buttons - "NEW", "EDIT", and "VIEW" - all of which render to one component. As a result, it is crucial for me to determine which specific button has been clicked in order to ...

Angular styling and form error issue

Hey there! I'm new to Angular and facing a major issue along with a minor styling problem. Let's start with the big one: <mat-form-field appearance="fill"> <mat-label>Password</mat-label> <input matInput ...

Tips for stopping a click from going through a fixed element to the one in the background

My website features a fixed positioned header with a search box, overlaying content below it (thanks to the higher z-index). When I click on the search box, an event handler is triggered. However, the click response also passes through the header to the ...

Adding JSON data to an array for Flot Diagram

I've been struggling with the task of organizing data into an array. The existing temp array is structured as follows: tmp[0][0] = "NY" tmp[0][1] = "52" tmp[1][0] = "FL" tmp[1][1] = "25" My goal is to transfer this data into a new array called data. ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...