javascriptimagethree.jsrenderon-the-fly

How can I load new material.map.image.src in background and then render


I am trying to change material.map.image.src on the fly when interacting with mouse, but each time i set the new image, the scene jitters while the image loads. to show the problem at its worst, i have linked the change to the onMouseMove event.

A working jittery example is here: Example

I am doing this in the onMouseMove event which is probably the wrong approach and my code is crude as I have tried to learn javascript in order to use three.js: monkey see, monkey do style.

Can anyone help me make the intersects[i].object.material.map.image.src = "/images/maisy.jpg"; work in the background...?

function onMouseMove(e) {
        e.preventDefault();
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
        raycaster.setFromCamera(mouse, camera);
        var intersects = raycaster.intersectObjects(scene.children);

        for (var i = 0; i < intersects.length; i++) {
            intersects[i].object.material.map.image.src = "/images/maisy.jpg";
            exit; // ensures foreground object is adjusted and not all behind it.
        }
    }

It is probably obvious to you all, but it has taken me some time to get this far and now I'm stumped.

Many thanks in advance to all who read,

James


Solution

  • Somewhere in your init code you would do:

    maisyTex = THREE.ImageUtils.loadTexture( "images/maisy.jpg" );
    

    with maisyTex being a global variable. Then in your code you would just do:

    intersects[i].object.material.map = maisyTex;