js实现3d图片轮播
实现3D图片轮播的方法
使用JavaScript和CSS 3D变换可以创建3D图片轮播效果。以下是实现方法:
基本HTML结构
<div class="carousel-container">
<div class="carousel">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
</div>
<button class="prev">Previous</button>
<button class="next">Next</button>
CSS样式设置
.carousel-container {
perspective: 1000px;
width: 500px;
height: 300px;
margin: 0 auto;
}
.carousel {
width: 100%;
height: 100%;
position: relative;
transform-style: preserve-3d;
transition: transform 1s;
}
.carousel img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
JavaScript实现逻辑
const carousel = document.querySelector('.carousel');
const images = document.querySelectorAll('.carousel img');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentIndex = 0;
const totalImages = images.length;
const angle = 360 / totalImages;
// 初始化3D布局
function setupCarousel() {
images.forEach((img, index) => {
const rotateY = angle * index;
img.style.transform = `rotateY(${rotateY}deg) translateZ(250px)`;
});
}
// 旋转到下一张
function nextSlide() {
currentIndex = (currentIndex + 1) % totalImages;
rotateCarousel();
}
// 旋转到上一张
function prevSlide() {
currentIndex = (currentIndex - 1 + totalImages) % totalImages;
rotateCarousel();
}
// 执行旋转
function rotateCarousel() {
const rotateY = -angle * currentIndex;
carousel.style.transform = `rotateY(${rotateY}deg)`;
}
// 事件监听
nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
// 初始化
setupCarousel();
增强交互效果
添加自动播放和悬停暂停功能:
let autoPlayInterval;
function startAutoPlay() {
autoPlayInterval = setInterval(nextSlide, 3000);
}
function stopAutoPlay() {
clearInterval(autoPlayInterval);
}
// 鼠标悬停暂停
carousel.addEventListener('mouseenter', stopAutoPlay);
carousel.addEventListener('mouseleave', startAutoPlay);
// 开始自动播放
startAutoPlay();
响应式调整
添加窗口大小变化时的调整:
function adjustCarousel() {
const containerWidth = document.querySelector('.carousel-container').offsetWidth;
const translateZ = containerWidth / 2 / Math.tan(Math.PI / totalImages);
images.forEach(img => {
const currentRotateY = img.style.transform.match(/rotateY\((\d+)deg\)/)[1];
img.style.transform = `rotateY(${currentRotateY}deg) translateZ(${translateZ}px)`;
});
}
window.addEventListener('resize', adjustCarousel);
这个实现创建了一个3D轮播效果,图片围绕Y轴旋转,形成环形排列。可以通过按钮控制旋转方向,也支持自动播放和响应式调整。







