css制作魔方
使用CSS制作3D魔方
通过CSS的3D变换和动画效果可以创建一个交互式魔方。以下是实现步骤:
HTML结构
<div class="cube">
<div class="face front">1</div>
<div class="face back">2</div>
<div class="face right">3</div>
<div class="face left">4</div>
<div class="face top">5</div>
<div class="face bottom">6</div>
</div>
CSS样式
body {
perspective: 1000px;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.cube {
position: relative;
width: 200px;
height: 200px;
transform-style: preserve-3d;
animation: rotate 10s infinite linear;
}
.face {
position: absolute;
width: 200px;
height: 200px;
opacity: 0.8;
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
color: white;
border: 2px solid black;
}
.front {
background: red;
transform: translateZ(100px);
}
.back {
background: orange;
transform: translateZ(-100px) rotateY(180deg);
}
.right {
background: blue;
transform: translateX(100px) rotateY(90deg);
}
.left {
background: green;
transform: translateX(-100px) rotateY(-90deg);
}
.top {
background: white;
transform: translateY(-100px) rotateX(90deg);
}
.bottom {
background: yellow;
transform: translateY(100px) rotateX(-90deg);
}
@keyframes rotate {
from { transform: rotateY(0) rotateX(0); }
to { transform: rotateY(360deg) rotateX(360deg); }
}
实现交互控制
移除自动旋转动画,添加鼠标控制功能:
document.addEventListener('mousemove', (e) => {
const cube = document.querySelector('.cube');
const x = e.clientX / window.innerWidth;
const y = e.clientY / window.innerHeight;
cube.style.transform = `
rotateX(${(y - 0.5) * 180}deg)
rotateY(${(x - 0.5) * 180}deg)
`;
});
制作可点击旋转的面
为每个面添加点击事件,实现局部旋转:
const faces = document.querySelectorAll('.face');
faces.forEach(face => {
face.addEventListener('click', () => {
const axis = face.classList.contains('top') ? 'X' :
face.classList.contains('bottom') ? 'X' :
'Y';
const direction = face.classList.contains('left') ? -90 : 90;
document.querySelector('.cube').style.transform +=
`rotate${axis}(${direction}deg)`;
});
});
响应式设计调整
添加媒体查询确保不同设备上的显示效果:
@media (max-width: 600px) {
.cube {
width: 150px;
height: 150px;
}
.face {
width: 150px;
height: 150px;
font-size: 30px;
}
.front { transform: translateZ(75px); }
.back { transform: translateZ(-75px) rotateY(180deg); }
/* 其他面类似调整... */
}
这些代码组合起来可以创建一个完整的3D CSS魔方,包含自动旋转、鼠标交互和面点击旋转功能。通过调整颜色、尺寸和动画参数可以获得不同的视觉效果。






