Is it possible to modify the radius of a circle by clicking on it using three.js?

My JavaScript code snippet draws circles and changes their color upon clicking. However, I am struggling to modify the radius/size of a circle individually when clicked, without affecting others. The documentation has not been helpful, and my attempts at modifying the code have been unsuccessful:

intersects[ 0 ].object.geometry.parameters.radius = 50;
intersects[ 0 ].object.geometry.radius = 50;
intersects[ 0 ].object.geometry.setRadius(50);

Here is the complete code for reference:

var container, camera, scene, geometry, mesh, renderer, controls, particles, colors;
var objects = [];

// DOM element...
container = document.createElement('div');
document.body.appendChild(container);

// Camera...
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 0, 75);

// Scene...
scene = new THREE.Scene();
scene.add(camera);

// Renderer...
renderer = new THREE.WebGLRenderer({
    clearAlpha: 1
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffffff, 1);
document.body.appendChild(renderer.domElement);         

// Scatter plot...
scatterPlot = new THREE.Object3D();
scene.add(scatterPlot);

// Make grid...
xzColor = 'black';
xyColor = 'black';
yzColor = 'black';


// Plot some random points...
circle = new THREE.CircleGeometry(5);

colors = [];
var max = 50;
var min = -50;

for (var i = 0; i < 10; i++) {          

    var object = new THREE.Mesh( circle, new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, opacity: 0.5 } ) );
    object.position.x = Math.random() * (max - min) + min;
    object.position.y = Math.random() * (max - min) + min;
    object.position.z = 0;                  

    scene.add( object );
    objects.push( object );

}

animate();

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

raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
document.addEventListener( 'mousedown', onDocumentMouseDown, false );

function onDocumentMouseDown( event ) {
    event.preventDefault();
    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( objects );
    if ( intersects.length > 0 ) {
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
        intersects[ 0 ].object.geometry.setRadius(50);
        var particle = new THREE.Sprite( particleMaterial );
        particle.position.copy( intersects[ 0 ].point );
        particle.scale.x = particle.scale.y = 16;
        scene.add( particle );
    }
}

Can anyone provide guidance on how to accomplish this? Additionally, any recommendations for finding accurate documentation would be appreciated.

Addendum:

  • I tried the following line of code:

    intersects[ 0 ].object.geometry.scale(1.1,1.1,1.1);

Now, the circles change size upon clicking, but it affects all circles instead of just one. This behavior doesn't seem logical to me...

Answer №1

Avoid scaling the geometry directly as it will affect all circles that use the same reference. Instead, focus on scaling the Mesh itself, which is a unique object within the scene. Similar to how you adjust the position, you can also modify the scale:

intersects[0].object.scale.set(1.1, 1.1, 1.1);

This code snippet will only scale the specific intersected Mesh and not impact others.

Creating new instances or cloning the Mesh repetitively can lead to memory leaks. The original Mesh will persist in the scene until removed, while duplicating the circle results in unnecessary creation of additional Geometry objects.

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

Is it possible to insert an image into a text box? If yes, what is the process for doing

Is there a way to create a text area where users can upload images with the click of a button, similar to how Orkut allows for image insertion? I want the user to be able to select an image to be uploaded and have it automatically added to the text area ...

What is the process for performing an Inner Join using SEQUELIZE?

My data is stored in two tables: Table 1: ID Name Email First row row Second row row Table 2: ID Number Status First row row Second row row I have defined JS models for each table. This is the model for Table 1: import Sequelize f ...

JavaScript Function for Shuffling an Array

Looking for advice on optimizing a function I'm developing. My goal is to: Double the frequency of numbers in an array Randomize the location of the values in the array. For instance: Imagine I have an array. [0,1,2,3] First, I need to dupl ...

Javascript synchronously making an AJAX request that times out

Currently, my JavaScript is set up to send data to a server when the page closes using synchronous AJAX (SJAX) request in `window.onbeforeunload`. However, this approach can cause the browser to freeze if the server or network connection experiences delays ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

Is it possible for my React component to automatically detect changes on the server and refresh itself accordingly?

I have been facing a challenge with my React components. One component is responsible for rendering a list of items, while another allows users to add new items by making an async call to the server. I am struggling to find a way for the list-rendering com ...

Chrome crashing due to toDataURL

Recently, I have been working on a Tile Renderer for three.js and so far, everything appears to be functioning correctly. The process is quite simple: a) It creates multiple cameras, b) Renders the scene using each camera c) Generates a 'toDataURL&a ...

What is the best approach for accessing values from dynamic or multiple form fields upon submission in React?

In my form, users have the ability to add Textfields in order to include additional items. However, I am facing a challenge when it comes to retrieving these items from the form upon submission. The Textfields are dynamically created by a component functi ...

JavaScript tutorial: Strategies for loading specific sections of a webpage initially

Many native apps, such as those on iOS, include a welcome page to keep users entertained while the app is loading. Currently, I am working on a Ruby on Rails web application (yes, it's a website!) I would like to incorporate a welcoming page into my ...

Convert the values in the array from strings to numbers

My array contains the following values: var items = [Thursday,100,100,100,100,100,100] I am retrieving these values from the URL query string which is why they are all in string format. I am looking for a way to make all columns except the first one as ...

Exploring data segments in Knockoutjs using various models

I'm trying to figure out why Knockout.js won't allow me to access specific parts of the model data. Could it be because I am binding the model to the div that contains all the submodels (such as the Form in this example), or am I approaching this ...

Ensure that the entire webpage is optimized to display within the viewport

My goal is to make the entire website fit perfectly into the viewport without requiring any scrolling. The main pages I am focusing on are index, music, and contact, as the other two pages lead to external sources (you can find the link at the bottom of th ...

Ways to determine if a website element is hidden from view

I am currently investigating the visibility of the following element: <ul class = 'pagination-buttons no-bullets'> https://i.sstatic.net/oOo7S.png When <ul class = 'pagination-buttons no-bullets'> is visible, its parent el ...

Resolving unexpected behavior with res.locals and pug integration

I have a function in my app.js that allows the user-id to be accessible in pug templates. app.use(function (req, res, next) { res.locals.currentUser = req.session.userId; next(); }); When logged in, I can access the id. However, when not logged in, t ...

Tips for altering the color of two circles when they overlap:

Hello, I am interested in creating an effect where two circles change color when they overlap. Specifically, I would like the overlapped section to become white to represent sets. var canvas = d3.select("canvas"), context = canvas.node().getContext( ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

Resolving Problems with setInterval in jQuery Ajax Calls on Chrome

Seeking assistance in returning the value of a specific URL periodically using jQuery and setInterval. Below is my current code snippet: $("form").submit(function() { setInterval(function(){ $('#upload_progress').load(&ap ...

What is the equivalent of this PHP array function in JavaScript/jQuery?

PHP is handling this scenario well. What would be the most efficient way to achieve a similar outcome in JS/jQuery? $statsArr['Status'][$s_id]['count'] = ($statsArr['Status'][$s_id]['count'] ?? 0) + 1; ...

What is the best way to prompt my bot to send a follow-up message once a user responds to a query?

I'm currently developing a system where a bot asks users questions, clears the messages after receiving their replies, and then proceeds to ask another question in a loop until all questions are answered. However, I'm facing an issue where the b ...

Disable button not necessary when validating checkboxes

I'm working on a simple function that involves 3 checkboxes. The goal is to disable the button if all checkboxes are unchecked, and enable it only when all three checkboxes are checked. function checkAll() { var checkbox1 = document.getElem ...