3D Perspective Card using JavaScript – Coding Torque

Share your love

Hello Guys! In this blog, We are going to make a card with a 3D perspective using javascript. We can use this type of effect on the payment page for showcasing the credit/debit details card. This will be a step-by-step guide including HTML and CSS. Let’s get started 🚀.

Before we start, here are some more JavaScript Games you might like to create:

1. Snake Game using JavaScript

2. 2D Bouncing Ball Game using JavaScript

3. Rock Paper Scissor Game using JavaScript

4. Tic Tac Toe Game using JavaScript

5. Whack a Mole Game using JavaScript

 

I would recommend you don’t just copy and paste the code, just look at the code and type by understanding it.

 

HTML Code 

<!doctype html>
<html lang="en">
    
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <title>3D Perspective using Tilt.js - @code.scientist x @codingtorque</title>
    </head>
    
    <body>
        <div class="container">
            <div class="card"></div>
        </div>
    </body>
    
</html>

 

Output Till Now

CSS Code 

Create a file style.css and paste the code below.

* {
    margin: 0;
    padding: 0;
}

body {
    background: black;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 15rem;
}

.container {
    position: relative;
    overflow: hidden;
    border-radius: 10px;
}

.card {
    background: url('../imgs/one.jpg') center center / cover;
    border-radius: 10px;
    height: 20rem;
    width: 15rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: hidden;
    z-index: -1;
    cursor: pointer;
    transition: 0.3s;
}

.card:hover {
    transform: scale(1.1);
}

 

Output Till Now

3D Perspective Card using JavaScript

JavaScript Code 

Create a file script.js and paste the code below.
const box = document.querySelector(".container");
const boxRect = box.getBoundingClientRect();

box.addEventListener('mousemove', e => {
    const xPosition = (e.clientX - boxRect.left) / boxRect.width
    const yPosition = (e.clientY - boxRect.top) / boxRect.height - 0.6
    const xOffset = -(xPosition - 0.6)
    const dxNorm = Math.min(Math.max(xOffset, -0.6), 0.6)
    box.style.transform = `perspective(1000px)
                            rotateY(${dxNorm * 45}deg)
                            rotateX(${yPosition * 45}deg)`
})

box.addEventListener('mouseleave', e => {
    box.style.transform = 'none'
})
Written by: Piyush Patil
If you have any doubts or any project ideas feel free to Contact Us
Hope you find this post helpful💖
Share your love