How to highlight 3d object on mouse hover

Hi guys. I have a .glb 3d objects: buildings. I want to highlight each building on mouse hover.
I find getHex / setHex attribute during researches, but I’n not sure how to use it or is it correct approach.

Thanks in advance.

I’ve enhanced the official glTF example with raycasting so you can actually select the model on click. The code then chances the diffuse color to a random value. The important code is:

var intersects = raycaster.intersectObject(scene, true);

if (intersects.length > 0) {
	
    var object = intersects[0].object;

    object.material.color.set( Math.random() * 0xffffff );

}

Demo: https://jsfiddle.net/41aun97x/1/

1 Like

Thanks a lot, this example helps me a lot. Can I have one more question please. Is it possible to remove color on mouse out?

Just save the reference to the current intersected object in a module scope variable and then restore the color in the mouseout event listener. The original color can be stored in Material.userData.

In docs, it says userData is an object that can be used to store custom data about the Material, but how to use or store original look of the object is not specify. Could you provide an example or a source to look through?

Well, if you only modify the diffuse color of the material, just store the old value before you change it. So:

material.userData.oldColor = material.color.getHex();

thanks a lot for your help.

Sorry for bringing up an older subject. I am trying to learn threes and I only just started learning javascript >_<

I tried changing your JSFiddle:


with userData, but can not remove the random Hex with userData oldColor

What makes sense to me is if you want to switch between states, you can ask if there is a property… and if there isn’t one, then it should be one
like this:
if ( material === “oldColor”) { material = “randomColor”; }
else { material = “oldColor”;

But where do you call this command for it to return the diffuse back to the original material? Like if you clicked outside of the model… or if you clicked on another model in the scene?

Sorry if this is a really basic question lol

You can store the clicked model in a global variable outside the onClick function, to change it back if you have not clicked the model.

var object // Global variable

onClick() {

    ....

    if (intersects.length > 0) {

        object = intersects[0].object;

        object.material.color.set( Math.random() * 0xffffff );
    }
    else { // stored object -> change back to #FFFFFF
        object.material.color.set( 0xffffff );
    }
}
1 Like

I’m embarrassed I missed something like global variable >_<
You are super cool for this! Thank you very much for taking time for me!

1 Like