0
<div style="margin-bottom: 200px">  
    <a href="#" onclick="cambio()"> sdsadasdas</a>
</div>

<div id="container"></div>
<div id="info"> </div>

I have an image using three.js which I need to change dynamically by others when I click on a button

<!-- <script src="three.min.js"></script> -->
<script>
    var camera, scene, renderer;

    var texture_placeholder,
    isUserInteracting = false,
    onMouseDownMouseX = 0, onMouseDownMouseY = 0,
    lon = 0, onMouseDownLon = 0,
    lat = 0, onMouseDownLat = 0,
    phi = 0, theta = 0;

    var imagen='HabitacionPrincipal'
    init(imagen);

    function cambio(){
    //What would I need to place here to be able to make the change dynamically?

    }

    function init(imagen) {
        var container, mesh;
        container = document.getElementById( 'container' );
        camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 );
        camera.target = new THREE.Vector3( 0, 0, 0 );
        scene = new THREE.Scene();

        var geometry = new THREE.SphereGeometry( 500, 60, 40 );
        geometry.applyMatrix( new THREE.Matrix4().makeScale( -1, 1, 1 ) );

        console.log(imagen)
            var material = new THREE.MeshBasicMaterial( {
                map: THREE.ImageUtils.loadTexture( imagen+'.jpg' )
            } );

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

        renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );

        window.addEventListener( 'resize', onWindowResize, false ); 
        animate();
    }
</script>

I need to change the image by a previously selected one

I tried this post but not sucessc

Threejs Change image at runtime

Towkir
  • 3,889
  • 2
  • 22
  • 41

1 Answers1

0

You need to make the variable globally accessible, instead of limiting its scope to the init() function.

Think of it as a Venn diagram, you have to place material outside init() and cambio() so that it's available to both. You can do this by declaring it on line 1:

var camera, scene, renderer, material;

Then, you can initialize material inside init() without using var:

function init(imagen) {
    // ...

    material = new THREE.MeshBasicMaterial( {
        map: THREE.ImageUtils.loadTexture( imagen+'.jpg' )
    } );

    // ...
}

Once you're ready to call cambio(), the material will be globally available, so you can access it and change its map:

function cambio(){
    material.map = THREE.ImageUtils.loadTexture( 'secondImage.jpg' );
}
M -
  • 26,908
  • 11
  • 49
  • 81