summaryrefslogtreecommitdiff
path: root/src/js/2dtilt.js
blob: c37dd64d6da80b37e795da9730a4a0a58eb436c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//check if mobile
if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) || window.orientation > 1) {
} else {
    window.onload = function() {

        let target = document.getElementsByClassName("tilt")[0];
        let content = target.getElementsByClassName("content")[0];
        let isMouseOver = false;
        let centerX;
        let centerY;
        let mouseX;
        let mouseY;

        function resetStyle() {
            target.style.transform = "";
            target.style.height = "0px";
        }

        function sizeControl() {
            var contentWidth = content.clientWidth;
            var contentHeight = content.clientHeight;
            target.style.width = `${contentWidth}px`;
            target.style.height = `${contentHeight}px`;
            window.requestAnimationFrame(sizeControl);
        }
        window.requestAnimationFrame(sizeControl);

        // tile effect

        function tiltEffect() {
            const deltaScale = 50.0;
            isMouseOver = true;
            var rect = target.getBoundingClientRect();
            centerX = rect.left + rect.width / 2;
            centerY = rect.top + rect.height / 2;
            target.style.transform = `translate(${ ( mouseX - centerX ) / deltaScale }px, ${ ( mouseY - centerY ) / deltaScale }px)`;
            requestAnimationFrame(tiltEffect);
        }

        target.addEventListener("mouseleave", () => {
            isMouseOver = false;
            target.style.transform = "";
        });

        document.addEventListener("mousemove", function(event) {
            mouseX = event.clientX;
            mouseY = event.clientY;
        });

        requestAnimationFrame(tiltEffect);

    };
}