使用css3实现魔方动画效果,核心是利用3D变换属性搭建三维场景,定位魔方的六个面,再通过animation属性配置旋转动画,让魔方实现自动旋转的效果。

实现原理说明
css3的3D变换需要先在父容器上开启3D渲染环境,通过transform-style:preserve-3d让子元素保持3D空间关系。魔方的六个面都是绝对定位的矩形,通过translateZ和rotate属性分别定位到立方体的前后左右上下六个位置。最后给魔方容器添加旋转动画,就能实现整体转动的效果。
完整实现代码
以下是完整的html和css代码,直接保存为html文件即可在浏览器中运行查看效果:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css3魔方动画</title>
<style>
/* 页面基础样式,让魔方居中显示 */
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
/* 3D场景容器,开启3D渲染环境 */
.scene {
width: 200px;
height: 200px;
perspective: 800px; /* 设置透视距离,值越小3D效果越强烈 */
}
/* 魔方容器,设置3D变换保留,添加旋转动画 */
.cube {
width: 100%;
height: 100%;
position: relative;
transform-style: preserve-3d; /* 子元素保持3D空间 */
animation: rotate 8s infinite linear; /* 无限循环线性旋转动画 */
}
/* 魔方每个面的基础样式 */
.face {
position: absolute;
width: 200px;
height: 200px;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
font-weight: bold;
color: #fff;
opacity: 0.9;
}
/* 前面:向Z轴正方向移动100px(魔方边长的一半) */
.front {
background-color: #e74c3c;
transform: translateZ(100px);
}
/* 后面:先绕Y轴旋转180度,再向Z轴正方向移动100px */
.back {
background-color: #3498db;
transform: rotateY(180deg) translateZ(100px);
}
/* 右面:先绕Y轴旋转90度,再向Z轴正方向移动100px */
.right {
background-color: #2ecc71;
transform: rotateY(90deg) translateZ(100px);
}
/* 左面:先绕Y轴旋转-90度,再向Z轴正方向移动100px */
.left {
background-color: #f1c40f;
transform: rotateY(-90deg) translateZ(100px);
}
/* 上面:先绕X轴旋转90度,再向Z轴正方向移动100px */
.top {
background-color: #9b59b6;
transform: rotateX(90deg) translateZ(100px);
}
/* 下面:先绕X轴旋转-90度,再向Z轴正方向移动100px */
.bottom {
background-color: #e67e22;
transform: rotateX(-90deg) translateZ(100px);
}
/* 定义旋转动画:绕X轴和Y轴同时旋转 */
@keyframes rotate {
0% {
transform: rotateX(0deg) rotateY(0deg);
}
100% {
transform: rotateX(360deg) rotateY(360deg);
}
}
</style>
</head>
<body>
<div class="scene">
<div class="cube">
<div class="face front">前</div>
<div class="face back">后</div>
<div class="face right">右</div>
<div class="face left">左</div>
<div class="face top">上</div>
<div class="face bottom">下</div>
</div>
</div>
</body>
</html>代码关键点解析
perspective属性设置在场景容器上,用来定义用户视点与3D元素之间的距离,数值越小,3D元素的透视变形越明显。transform-style:preserve-3d必须设置在魔方容器上,否则六个面会被拍扁到2D平面,无法形成立方体结构。- 每个面的
translateZ(100px)的数值是魔方边长的一半,因为魔方容器宽高是200px,一半就是100px,这样才能让六个面刚好组成一个闭合的立方体。 - 动画的
infinite表示无限循环,linear表示匀速旋转,你可以根据需要调整动画时长和旋转角度。
效果调整建议
如果想要修改魔方的大小,只需要调整.scene和.cube的宽高,同时把每个面的宽高和translateZ的数值同步修改即可。如果想要改变旋转方式,可以调整@keyframes里的旋转角度,比如只绕Y轴旋转,就把rotateX的数值去掉,只保留rotateY的变化。