Is there a way to include an item into a three.js environment during a mouse click event?

Is it possible to dynamically add a 3D object to a three.js scene after it has been initialized and the user triggers a click event? How can this be achieved within the existing code structure provided?

You can find a prepared scene setup in this working example.

var camera, scene, renderer;
var geometry, material, mesh;

window.addEventListener("click", addCube, false);

function addCube() {
    alert("Implement the code to add an object here!");
}

var init = function () {

    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 500;

    scene = new THREE.Scene();

    geometry = new THREE.CubeGeometry(200, 200, 200);
    material = new THREE.MeshBasicMaterial({
                color: 0x000000,
                wireframe: true,
                wireframeLinewidth: 2
            });

    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

}

var animate = function () {

    requestAnimationFrame(animate);

    mesh.rotation.x = Date.now() * 0.0005;
    mesh.rotation.y = Date.now() * 0.001;

    renderer.render(scene, camera);

}

init();
animate();

Answer №1

Retrieve element's ID

var selectedElement = document.getElementById("element-id");

Attach event listener

selectedElement.addEventListener("click", addCube, false);


function addCube(){
   var geometry = new THREE.CubeGeometry( 200, 200, 200 );

   var material = new THREE.MeshBasicMaterial( { color: 0x000000 } );

   var mesh = new THREE.Mesh( geometry, material );

  //scene is accessible globally
   scene.add(mesh);
}

Alternatively, using jQuery

$(element).click(addCube);

Answer №2

Check out this interactive demo featuring a rotating cube:

function addCube(){
         var r = Math.random() + 0.5;
     var geometry = new THREE.CubeGeometry( 200 * r, 200 * r, 200 * r);

     var material = new THREE.MeshBasicMaterial( { color: 0x00FF00,
                wireframe: true,
                wireframeLinewidth: 2 } );
                var mtmp = new THREE.Mesh( geometry, material );
        cubes.push( mtmp );

    //scene is global
        scene.add(mtmp);


  }

var animate = function () {

     requestAnimationFrame(animate);

      for (var i = 0; i < cubes.length; i++) {
        console.log(i);
        //scene.add(cubes[i]);
        cubes[i].rotation.x = Date.now() * 0.0005 * (1+i);
                cubes[i].rotation.y = Date.now() * 0.001 * (1+i);
      }


            renderer.render(scene, camera);
    }

http://jsfiddle.net/Lkk1zhkt/2/

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

The power of Ng-show and filtering

What I am aiming for is to display a complete list of cities as soon as the page is loaded. Once a user clicks on a checkbox next to a city, my goal is to utilize ng-show/ng-hide in order to display the results specific to that city while hiding those of ...

Struggling to update the inner content of a div container

For some reason, I'm having trouble updating the inner html content of a specific div element. <div class="emoji-wysiwyg-editor form-control" data-id="83fa07d0-2bab-4c02-8bb6-a2133ae64bbd" data-type="input" placeholder="Chat Message" contenteditab ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

Issue with updating the vertices in three.js EdgesGeometry is causing the Line Segments to not be updated as expected

I have created multiple three.js objects. I have observed that the 'other' objects, designed as Mesh/Geometry/Material, update as expected after calling verticesNeedUpdate() Furthermore, I have two wireframe objects that were designed in this m ...

Jquery Error: Unable to split object

Why am I getting an error saying "Uncaught TypeError: Object # has no method 'split'" when trying to run this page by clicking on the dropdown and triggering a change event that sends an AJAX request? <html xmlns="http://www.w3.org/1999/xhtm ...

Adjust picture based on the MaterialUI slider's value

I want to incorporate a discrete Slider component from Material UI into my React web app. The goal is to have the user change a picture every time they adjust the slider value, with the new image displayed in a specific div. I am wondering how I can achiev ...

As I spun four images along the outer edge of a circular border, one image came to a halt at 90 degrees, revealing its content. Now, I am looking to enlarge that particular

I managed to rotate four images around a circular border and stop one image at every 45-degree angle. However, I am struggling to enlarge the image that stops at 90 degrees on the website while still showing the content of the respective image when it reac ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

Sending user input data to a function in a React component

I am currently facing a challenge where I must retrieve the value of an input field in order to initiate an API request. Here is my current setup: import React, { Component } from 'react' import axios from 'axios'; const fetchWeather ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

What is causing the consistent error message "unable to read property 'logged' of undefined"?

Here is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie- ...

Unraveling the mysteries of this PHP-generated object

Need help with iterating over a JSON object generated by PHP code in response to a web service request. Looking for guidance on rendering sub-objects in a select list, especially those with value indexes. Can someone provide assistance on populating a sel ...

Tips for postponing the first button event in Vue 3 and JavaScript

My current task involves setting up a button event in Vue 3 that triggers a setTimeout countdown on the button before redirecting to another page. The event function has a conditional statement that initiates a countdown from 5 to 0 as long as the countVal ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

I am having trouble with setInterval not functioning as expected. I am trying to make a function repeat every 500ms using setInterval, but it seems to be ineffective

var direction; function movement(){ switch(direction){ case 1: positionX = positionX + 10; break; case 2: positionX = positionX - 10; break; case 3: positionY = positionY - 10; bre ...

Configuring route for serving static files in an Express server

I'm completely new to working with express, but I am eager to learn and follow the best practices. My goal is to serve files like CSS or index.html from a folder called 'public'. I have seen examples using .use and .get methods as shown belo ...

Ways to include additional details in each row of an autocomplete feature

I have successfully implemented autocomplete for venues worldwide, but now I want to display the address of each venue below its name. For example, if the autocomplete suggests the venue name as ABCD, I want the address of that venue to appear right benea ...

What is causing a 500 internal error in Django when using Ajax?

Can someone help me troubleshoot why I keep receiving a 500 internal error when trying to execute an Ajax function? I attempted to send the response from view.py to the Ajax function in two different ways: using JsonResponse (see 'else' section i ...

"Enhancing Functionality: A Detailed Guide on Callback Functions in Express

Currently, I am expanding my coding skills by learning express/Node, transitioning from C and PHP/MySQL. The MDN tutorial on express has been incredibly helpful in my learning journey, making everything straightforward. Thanks to the Mozilla teaching team, ...