3D卡片旋转动效-鼠标跟随

使用纯css 实现3D效果,以及借助JavaScript绑定鼠标事件

3D卡片旋转动效-鼠标跟随

效果展示:

HELLO! WELCOME CHIMENG BLOG

HTML代码:

<h1>HELLO! WELCOME HAIJING CLASS</h1>
    <div class="card" id="card">
        <div class="card-shine" id="card-shine"></div>
        <div class="card-shadow"></div>
        <div class="card-layer"></div>
    </div>

CSS代码:

*{
    margin: 0;
    padding: 0;
}

body,
html{
    height: 100vh;
    width: 100vw;
    overflow: hidden;
    transform-style: preserve-3d;
    perspective: 439px;
}

div{
    transform-style: preserve-3d;
    cursor: pointer;
    transition: all 0.1s;
}

h1{
    text-align: center;
}
.card{
    width: 200px;
    height: 350px;
    margin: 0 auto;
    position: relative;
    top: 150px;
    /* transform: rotateX(20deg); */
}

.card-shine{
    position: absolute;
    top: 0px;
    bottom: 0px;
    left: 0px;
    right: 0px;
    border:  2px solid black;
    z-index: 8;
    border-radius: 20px;
    /* background: linear-gradient(65deg,rgb(97, 89, 89),#fff); */
}

.card-shadow{
    position: absolute;
    top: 5%;
    left: 5%;
    width: 90%;
    height: 90%;
    z-index: 0;
    box-shadow: 0px 8px 20px 0px rgba(146, 37, 37, 0.7);
}

.card-layer{
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 20px;
    background-image: url(https://chimengblog.com/wpimg.php);
    background-size:cover;
    overflow: hidden;
    z-index: -2;
    box-shadow: 80px 50px 0px 6px rgba(127, 129, 115, 0.2);
}

JavaScript代码:

<script>
        const movelimit = document.getElementById("card");
        const card = document.getElementById("card");
        const cardshine = document.getElementById("card-shine");
        movelimit.addEventListener("mousemove", (e) => {
            window.requestAnimationFrame(function(){
                movecard(e.clientX, e.clientY);
            });
        });
        const speed=5;
        function movecard(x, y){
            let box = card.getBoundingClientRect();
            let calcX=(y - box.y -(box.height / 2)) / speed;
            let calcY=(x - box.x - (box.width / 2)) / speed * -1;
            let calcZ=(box.height*box.y)/60;
            card.style.transform="rotateX"+"("+calcX+"deg"+")"+"rotateY"+"("+calcY+"deg"+")";
            cardshine.style.background = "linear-gradient" + "(" +calcZ+ "deg" + "," + "#00000000" + "," + "rgb(255, 98, 56,0.3)"+ ")";
        }
        movelimit.addEventListener("mouseleave", (e) => {
            window.requestAnimationFrame(function(){
                card.style.transform="rotateX(0) rotateY(0)";
                cardshine.style.background="rgba(255,255,255,0)";
            });
        });
    </script>
© 版权声明
THE END
喜欢就支持一下吧
点赞159赞赏 分享
评论 共12条

请登录后发表评论