Can anyone help me understand how to retrieve accurate coordinates in Three.js when a user is dragging their mouse?

I am currently working with ThreeJS and I have a requirement to create a rectangle as the user clicks and drags their mouse.

Using ThreeJS library for this purpose.

    function onDrag(event) {
        if (!isDrawing) { return; }
        // The rectangle should follow the users mouse 
        var clientX = (event.pageX - startPosition.x) / 50;
        var clientY = (event.pageY - startPosition.y) / 50;
        var vertices = geometry.vertices;
        vertices[1].x = -clientX * -1;
        vertices[2].x = -clientX * -1;
        vertices[2].z = -clientY * -1;
        vertices[3].z = -clientY * -1;
        geometry.verticesNeedUpdate = true;
    }

// To view the complete code, please visit: https://jsfiddle.net/shawnswebsites/tcpakwgL/1/

Even though the rectangle should seamlessly follow the user's mouse after clicking down, it seems that there is an issue where the rectangle is smaller than intended. Could someone kindly spot what may be going wrong in my implementation?

Answer №1

You may be blending different spaces in your fiddle, which is why it's important not to directly assign window coordinates to vertex data. Instead, consider always working in world space by utilizing the output of your current raycasting logic. Here's an example:

function onDrag( event ) {

    if ( ! isDrawing ) return;

    var current = get3DPosition( event );

    var x = current.x;
    var z = current.z;

    geometry.vertices[ 1 ].x = x;
    geometry.vertices[ 2 ].x = x;
    geometry.vertices[ 2 ].z = z;
    geometry.vertices[ 3 ].z = z;
    geometry.verticesNeedUpdate = true;

}

Check out the demo: https://jsfiddle.net/qw03d14o/1/

I also needed to make some adjustments to ensure that the plane is positioned correctly above the ground without any y-offset. I've included polygonOffset and polygonOffsetFactor for the respective material to prevent z-fighting issues.

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

Sorting rows by words and numbers in JavaScript explained

Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed. ID Name Inventory Volume 1 Rachel Data is not enough 2 Ross 100 3 Monica 1 ...

Troubles experienced when utilizing node-jsdom in a loop

I am currently in the process of extracting data from a series of HTML pages. To gain access, I need to include certain parameters in my queries. These parameters are stored in a JSON format as shown below: [ {"NM":"bla", "Code":"a12312"}, {"NM":"blabla", ...

Choose2 - Dynamic search with auto-complete - keep track of previous searches

Currently, I am utilizing Select2 version 3.5.1 and have successfully implemented remote data loading with the plugin. However, I have a query regarding enhancing the search functionality. Below is a step-by-step explanation of what I aim to achieve: Cre ...

fuel ux checkbox mark all

I am having trouble implementing a feature where all checkboxes are selected when clicking on a specific checkbox. <div class="checkbox" id="myCheckbox2"> <label class="checkbox-custom" data-initialize="checkbox"> <input class="sr-onl ...

Navigating with ExpressJS

I am looking to enhance the flexibility of routing for handling slashes, such as app.get('/home/pages') The router should be able to manage ////home///pages /home/pages//// etc... requests. I have a potential solution in mind, but it requ ...

Adding an HDRi Equirectangle map in ThreeJS requires careful consideration to ensure the scene is properly lit while maintaining a transparent background

How can I incorporate HDRi lighting with an HDR EQUIRECTANGLE Texture into my scene while keeping the image transparent? I am sourcing images from the HDRI Haven website. Can you provide guidance on how to accomplish this? ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Problems arising from the usage of setInterval within the useEffect hook

I have encountered an issue while trying to use setInterval within useEffect. To ensure functionality, I moved the logic to a separate function and it works perfectly; alternating between two images every 3 seconds as intended. const rotateImages = (img) ...

Launch a modal from a separate webpage

I've been trying to implement a modal using Bootstrap 4, and after referring to the documentation, it seems to be working smoothly. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <scri ...

Has the removal of Javascript conditional compilation been confirmed in IE11?

I have been using javascript conditional compilation to determine the version of the IE Trident engine: var ieVersion = undefined; /*@cc_on ieVersion = Math.floor(@_jscript_version); @*/ Despite working fine for IE8, 9, and 10, in IE11, the conditiona ...

What sets apart express.Router() from using multiple express() objects?

When utilizing the latest express 4 router, it becomes possible to organize various route paths into separate files like the following example: // Inside cars.js const router = express.Router(); router.get('/brands', function(req, res) { ... } ...

Execute a jQuery focus() function on a textarea element within a dynamically added form on the webpage

Whenever I dynamically insert a new form onto the page using clone(), my goal is to have the textarea within the form automatically focused. However, despite trying out the code below, it seems like it's not functioning as expected: .on('click&a ...

Preview multiple images while uploading with V-for in Vue JS

Having trouble displaying images in a loop using :ref I've implemented FileReader() to read the field. Vue Component <div v-for="(image, index) in imgFile" :key="index"> <img :ref="'image'+parseInt( index )"> {{image.name}} ...

The button similar to Facebook does not function properly when using fancybox

My photo gallery uses fancybox, and when fancybox is open a like button appears outside the title. However, the Facebook like button doesn't seem to work. Here is my JavaScript code: $(".fancyboxi").fancybox({ padding: 0, openE ...

JavaScript error occurs when the max old space size is enlarged, resulting in an invalid size

Encountering an error while attempting to compute a sha256 hash of a large buffer (~300 MB) using the hash.js library: # # Fatal error in , line 0 # Fatal JavaScript invalid size error 169220804 # # # #FailureMessage Object: 0x7ffd6dc623c0 1: 0xbe6ad1 [/ ...

JavaScript: Implementing a retry mechanism for asynchronous readFile() operation

My goal is to implement a JavaScript function that reads a file, but the file needs to be downloaded first and may not be immediately available. If an attempt to access the file using readFile() fails and lands in the catch block, I want to retry the actio ...

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Are you familiar with a cutting-edge HTML5-powered, heritage-defying JavaScript framework?

Which cutting-edge framework should I choose to fully utilize the latest HTML5 technologies provided by modern browsers like Firefox 7, Safari 5, and Chrome 14? I have no need to support any older browsers such as IE, Firefox, or Chrome versions prior to t ...

What is the best way to generate a new object by combining elements from an array and another object?

Attempting to create a new object by using an existing array. The goal is to generate an object that displays the following: { jack: 'jack', content: 'ocean'}, { marie: 'marie', content: 'pond'}, { james: 'jame ...

What is the process for converting this value to a floating point

Here is the code snippet I am working with: $wage = array(); foreach ($result3 as $row3) { $wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']'; } if ($userid == 0 ) { $age= ""; ...