Issue with changing color of intersectObjects in Three.js not being properly registered [example code in jsfiddle]

I'm encountering an issue where I can't seem to change the color of a cube when someone hovers over it. I've simplified the code as much as possible.

Click here for the code

<script>
var container;
var scene, camera, renderer, mouse, raycaster;
var grid_items = [];

init();
grid();
render();

function init() {

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

    scene = new THREE.Scene();
    raycaster = new THREE.Raycaster();
    mouse = new THREE.Vector2();

    camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set( 500, 800, 1300 );
    camera.lookAt( new THREE.Vector3() );

    // Lights
    var ambientLight = new THREE.AmbientLight( 0x606060 );
    scene.add( ambientLight );

    var directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.x = Math.random() - 0.5;
    directionalLight.position.y = Math.random() - 0.5;
    directionalLight.position.z = Math.random() - 0.5;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    var directionalLight = new THREE.DirectionalLight( 0x808080 );
    directionalLight.position.x = Math.random() - 0.5;
    directionalLight.position.y = Math.random() - 0.5;
    directionalLight.position.z = Math.random() - 0.5;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    renderer = new THREE.CanvasRenderer();
    renderer.setClearColor( 0xf0f0f0 );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild(renderer.domElement);

    window.addEventListener('mousemove', onDocumentMouseMove, false );
}

function grid(){
    var geometry = new THREE.BoxGeometry(100, 100, 100);
    var material = new THREE.MeshBasicMaterial({ color: 0x0000ff });
    var cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
    grid_items.push(cube);
}

function onDocumentMouseMove(event) {

    mouse.x = (event.clientX / renderer.domElement.width) * 2 - 1;
    mouse.y = - (event.clientY / renderer.domElement.height) * 2 + 1;

    console.log(mouse.x+"-"+mouse.y);

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(grid_items);
    if (intersects.length > 0) {
        for (var i = 0; i < intersects.length; i++) {
            console.log("OBJECT "+intersects[i])
            intersects[i].object.material.color.set(0xff0000);
        }
    }
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);

    render();
}

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

Answer №1

Make sure to re-render the scene after changing the color of an object. Insert a call to render(); immediately after adjusting the colors:

if (intersects.length > 0) {
     for (var i = 0; i < intersects.length; i++) {
        console.log("OBJECT "+intersects[i]);
        intersects[i].object.material.color.set(0xff0000);
    }
    render();
}

See the updated demo here: http://jsfiddle.net/pgd3d5rf/1/

Answer №2

When using the CanvasRenderer(), your code does not seem to function properly. However, if you switch to the WebGLRenderer(), and include a render() call at the conclusion of your onDocumentMouseMove() function, it should start working as expected.

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

Setting up Jplayer as an audio player: A step-by-step guide

I am looking to incorporate a Jplayer audio player into my project, but I am struggling to find any documentation or resources that provide instructions on what components to include and how to set it up. If anyone has experience with using the Jplayer au ...

Disabling the submit button on an MC form - step by step guide

In order to create a multiple-choice question with radio buttons, each question must have only one answer choice. Each question should provide three options for the user to select from. It is necessary to validate whether the user has answered every questi ...

Steps to extract date selection from a datepicker using jQuery

I recently implemented this code snippet to utilize datepicker for displaying dates: $(document).ready(function(){ $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function (selected) { var dt = new Date(selected); ...

hyperlinked text that automatically updates with the current date (using metarefresh)

I want to insert a date variable into a URL based on the current date. Specifically, I am looking to create a link from SharePoint that directs a user to the relevant files in a shared drive. My initial idea is to use an HTML page with a meta refresh that ...

Send data in JSON format along with an identifier using Jquery AJAX

I am having trouble sending JSON data along with 2 IDs using a jQuery AJAX post. Despite my efforts, I can't seem to get it working. Here is the code snippet in question: try { var surveyID = localStorage.getItem("surveyId"); var userDetails ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

Is it possible for the Vue.js application to show the component right where the cursor is located in the textarea?

I am looking to create a Vue.js component with the following capabilities: As the user types in the textarea, I want the component to display recommended words. For instance, if the user types the letter s, I want a dropdown list to appear with words ...

Trigger an alert when a button is clicked and redirect the user to an newly opened tab

I recently created a button with a link that opens in a new tab. I also implemented some JavaScript to display an alert. Everything is working as expected, but after the user clicks "OK" on the alert, they remain on the same page. I would like to automati ...

javascript array filled in an unusual manner

Currently, I am developing an angular application that involves creating a custom array of services called Workbooks, each containing an array of services known as Views. However, while populating the array using a simple for loop, I encountered some unexp ...

Remove the post by utilizing the $.ajax function

I am just starting out with using $.ajax and I'm not very familiar with it. I have a button that is meant to delete a user post based on the article ID provided. <button type="button" onclick="submitdata();">Delete</button> When this but ...

What is the best way to insert a variable URL in JavaScript code?

When working with PHP, I often create a declaration similar to the following (taken from an example on Stack Overflow): <script type="text/javascript"> var templateurl = "<?php bloginfo('template_url') ?>"; </script> Subse ...

Deactivate the focus state when hovering over different items in the navigation bar

Currently facing an issue with my Navbar items having underline animation on hover. Once clicked, the animation persists. However, when hovering over a neighboring navbar item, the underlines appear next to each other, creating the illusion of one long lin ...

What is the best way to keep calling an AJAX function until it receives a response from a previous AJAX call

I am looking to continuously call my ajax function until the previous ajax call receives a response. Currently, the page is loading every second and triggering the ajax function, but I want it to keep calling the ajax function until the previous one has c ...

Receive notification of alert content when it is displayed

Having an HTML page with the following script: <Script> function Run() { alert("The Content Here"); return true; } </script> <button onclick="Run();">I Want It Now</button> If I were to open this page using firefox or Chrome, and ...

Stacked column tooltip displaying an array of 3 values

I am working with a json code that looks like this: [[1385420403000,9.86,6.91],[1385506802000,11.89,6.57],[1385593203000,14.11,10.58],[1385679602000,9.1,8.9],[1385766003000,13.59,7.53],[1385852402000,10.68,6.69],[1385938803000,11.03,10.52],[1386025202000, ...

Nodejs and express authentication feature enables users to securely access their accounts by verifying their identity before they

I am currently working on a straightforward registration page that needs to save user input (name, email, password) into a database. My tools for this task are express and node. What I am experimenting with is consolidating all the database operations (suc ...

Having trouble with the mongoose virtual field being undefined while using an arrow function?

Hey, I'm exploring the world of mongoDB! Here's the schema I created: const userSchema = new mongoose.Schema({ firstName:{ type:String, required:true, trim:true, min:3, max:20 }, lastName:{ ...

Tips for successfully sending parameters in a Google Geocoding request

Dealing with an array of objects containing addresses, each with four fields. The first field is the current location (store), while the others provide address information. The challenge is ensuring that I end up with a result in the format key:value (sto ...

Is it just me or does Img never work, no matter what the "src" is?

I am implementing Google's React example of a "Complex Grid" (located here) to create a Card-like layout. This is how the code appears: return ( <div className={classes.root}> <Paper className={classes.paper} ...

"Type Error: Attempting to assign a value to a const variable by declaring it as let while importing a variable from another file

Within JavaScript(Node.JS), I created a config.js file as shown below to export a variable named "name": Config.js export let name = "ayush"; Then, I imported the variable "name" into the index.js file index.js import {name} from "./config.js"; name = ...