Search code examples
javascripthtmlcsstransformperspective

Mouse coordinate based perspective rotation with centered div [Javascript]


Second question I've asked, so if I need to add anything else, let me know please!

Been looking everywhere to try and understand concepts, but I feel like I am over thinking it. What I am trying to do is base "transform: rotateX("x"deg)" off of the x location of the users cursor proportionately from the size of the window. Here is a gif that does what I want, but they use matrix3D instead of just transform's rotate.

http://i.imgur.com/tUZSLXA.gif

Here is a js fiddle of what I have so far.
https://jsfiddle.net/z7bet2sw/

JS:

function rotate() {
    var x = event.clientX;

    var w = window.innerWidth;
    var midpoint = w / 2;

    // restrictions for rotation
    if (x > -20 && x < 20) {


        document.getElementsById("logo").style.transform = "perspective(550px)" + "rotateY(" + x + "deg)";
    } else {

    }
}

document.addEventListener("mousemove", rotate);

Thanks!


Solution

  • You need to pass the event parameter to rotate function from addEventListener, and also you need to calculate a relative position from the x coordinates to get a value between -20 and 20:

    function rotate (event) 
    {
        var x = event.clientX;
        var w = window.innerWidth;
        var midpoint = w / 2;
        var pos = x - midpoint;
        var val = (pos / midpoint) * 20;
        var logo = document.getElementById ("logo");
        logo.style.transform = "perspective(550px) rotateY(" + val + "deg)";
    }
    
    document.addEventListener("mousemove", function(event)
    {
        rotate(event)
    }, false);
    

    JSFiddle