akella / webgl-mouseover-effects

Demos for the tutorial on how to achieve an interactive mouseover/hover effect
https://tympanus.net/codrops/?p=49069
MIT License
346 stars 61 forks source link

Placing the images in the right position #25

Open ahujasid opened 5 months ago

ahujasid commented 5 months ago

I was following the Codrops tutorial for this and managed to get it to work, but I can't figure out how to place the images in the threejs canvas in the same place as the existing image in the DOM. Any tips on how to do that?

This is the code right now:

function createMeshForImage(img, texture) {
    let bounds = img.getBoundingClientRect();
    let aspect = window.innerWidth / window.innerHeight;
    let width = bounds.width / window.innerWidth * aspect;
    let height = bounds.height / window.innerHeight * aspect;
    let geometry = new THREE.PlaneGeometry(width, height);
    let material = new THREE.MeshBasicMaterial({ map: texture });
    let mesh = new THREE.Mesh(geometry, material);
    mesh.userData.bounds = img.getBoundingClientRect();

    let x = (bounds.left + bounds.width / 2 - window.innerWidth / 2) / window.innerWidth * aspect;
    let y = -(bounds.top + bounds.height / 2 - window.innerHeight / 2) / window.innerHeight * aspect;
    mesh.position.set(x, y, 0);

    return mesh;
}