I'm

Developer, Designer, Photographer

GET IN TOUCH

  • Buk-gu, Busan, Republic of Korea
  • ungdoli0916@naver.com
  • Kakao ID : Ungdoli
Your message has been sent. Thank you!
(즐거웅코드) 자바스크립트 마우스 방향을 따라 회전하는 객체 만들기

· 즐거'웅' 코드 (Source)/HTML & CSS & JAVASCRIPT
2021. 9. 30. 19:21

반응형

[즐거'웅'코드] 목차

  1. 예제 소스
  2. 구현 예시
예제 소스
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
<style>
    #container {
        height: 100vh;
        width: 100vw;
        display: flex;
        align-items: center;
        justify-content: center;
    }
 
    #container #content {
        border: 2px solid #000000;
        height: 100px;
        width: 100px;
        position: absolute;
    }
</style>
 
<div id="container">
    <div id="content"></div>
</div>
 
<script>
    let $constrain = 20;
    let $container = document.getElementById("container");
    let $content = document.getElementById("content");
 
    function transforms(x, y, el) {
        let $box = el.getBoundingClientRect();
        let $calcX = -(y - $box.y - ($box.height / 2)) / $constrain;
        let $calcY = (x - $box.x - ($box.width / 2)) / $constrain;
 
        return "perspective(500px) "
            + "   rotateX("+ $calcX +"deg) "
            + "   rotateY("+ $calcY +"deg) ";
    }
 
    function transformElement(el, xyEl) {
        el.style.transform  = transforms.apply(null, xyEl);
    }
 
    $container.onmousemove = function(e) {
        let $xy = [e.clientX, e.clientY];
        let $position = $xy.concat([$content]);
 
        window.requestAnimationFrame(function(){
            transformElement($content, $position);
        });
    };
</script>
구현 예시
반응형