Interactive 3D Rotating Gallery In JavaScript

Category: Javascript , Slider | September 18, 2024
Authorariyojoey
Last UpdateSeptember 18, 2024
LicenseMIT
Views390 views
Interactive 3D Rotating Gallery In JavaScript

This is a 3D perspective rotating gallery that automatically cycles through a series of images displayed on a 3D ring.

It provides a dynamic and interactive way to present product images, portfolio highlights, or any collection of visuals where you want to create a memorable browsing experience.

How to use it:

1. Add your image to the gallery. Note that each image should wrapped in a span tag with a unique --i value, which controls the image’s initial position on the 3D ring, incrementing by 1 for each subsequent image.

<div class="image-container">
  <span style="--i: 1">
    <img src="1.jpg" title="image">
  </span>
  <span style="--i: 2">
    <img src="2.jpg" title="image">
  </span>
  <span style="--i: 3">
    <img src="3.jpg" title="image">
  </span>
  ... more images here ...
</div>

2. To allow users to manually cycle through the images, include the following HTML for the navigation buttons:

<div class="btn-container">
  <button class="btn" id="prev">Prev</button>
  <button class="btn" id="next">Next</button>
</div>

3. The required CSS that creates the 3D effect and styles the gallery elements:

.image-container{
  position:relative;
  width:200px;
  height:200px;
  transform-style: preserve-3d;
  transform: perspective(1000px) rotateY(0deg);
  transition: transform 0.7s;
}
.image-container span{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  transform: rotateY(calc(var(--i) * 45deg)) translateZ(400px);
}
.image-container span img{
  position:absolute;
  left:0;
  top:0;
  width:100%;
  border-radius: 5px;
}
.btn-container{
  position:relative;
  width:80%;
}
.btn{
  position: absolute;
  bottom:-80px;
  background-color: orangered;
  color:white;
  padding:10px 20px;
  border-radius: 5px;
  border:none;
  cursor: pointer;
}
.btn:hover{
  filter:brightness(1.5);
}
#prev{
  left:20%;
}
#next{
  right:20%;
}

4. Handles the automatic rotation and button click events with JavaScript.

const imageCon = document.querySelector(".image-container");
const prevEl = document.getElementById("prev");
const nextEl = document.getElementById("next");
let x=0;
let timer=0;
prevEl.addEventListener("click",()=>{
  x=x+45;
  clearTimeout(timer);
  updateImage();
});
nextEl.addEventListener("click",()=>{
  x=x-45;
  clearTimeout(timer);
  updateImage();
});
function updateImage(){
  imageCon.style.transform=`perspective(1000px) rotateY(${x}deg)`;
  timer=setTimeout(()=>{
      x=x-45;
      updateImage();
  },3000);
}
updateImage();

You Might Be Interested In:


Leave a Reply