最近在学习 three.js在拿example中的项目练手,用了一整天的时间模仿了一个炫酷的元素周期表,在原有的基础上进行了一些改变。下面我会逐步讲解这个项目,算是加深理解,让大家提提意见。
因为我未搭建个人服务器。截几张图给大家看看效果我做的效果(大部分是和原来的一样)。可能一部分人已经见过这个经典动画了。(这里是原项目地址:threejs.org/examples/cs…)
除了优化了原来的HELIX和GRID形式的的排版之外,我用另外一种方式也创建了两种自定义的排版方式。等会分享给大家。
下面是GitHub仓库地址,文件很简单,就一个HTML文件。想自己手动实现或者拿去用的可以看一下。喜欢的给颗星星,不胜感激(请忽略代码中的注释哈哈)。
下面开始分析这个小项目
技术栈
- HTML, CSS3, Javascript
- three.js, tween.js
- 三角函数
实现原理
- 利用three.js提供的CSS3DRenderer渲染器,通过CSS3转换属性将分层3D转换应用于DOM元素。其实就是包装一下DOM元素,可以像操作three.js中Mesh对象一样去操作DOM元素。本质上还是利用CSS3的3D动画属性。这个项目就是操作转换后DOM元素的position和rotation的属性值来创建动画
- 使用轻量级动画库tween'补间'控制DOM元素position和rotation属性值的过渡。
- 确定不同排版的每一个DOM元素的position和rotation(部分排版需要确定rotation)的值,并将之保存在THREE.Object3D的子对象的position属性中(也可以是一组想象数组后面我会详细讲解),然后使用‘补间’将DOM元素的position和rotation像其保存的对应属性值过渡。
话不多说,直接上代码。
HTML结构
<div id="container">
<!-- 选中菜单结构 start-->
<div id="menu">
<button id="table">TABLE</button>
<button id="sphere">SPHERE</button>
<button id="sphere2">SPHERE2</button>
<button id="plane">PLANE</button>
<button id="helix">HELIX</button>
<button id="grid">GRID</button>
</div>
<!-- end -->
</div>复制代码
HTML部分非常简单仅仅是一个包含六个控制转换的按钮的选择栏,下面看看他们的样式
#menu {
position: absolute;
z-index: 100;
width: 100%;
bottom: 50px;
text-align: center;
font-size: 32px
}
button {
border: none;
background-color: transparent;
color: rgba( 127, 255, 255, 0.75 );
padding: 12px 24px;
cursor: pointer;
outline: 1px solid rgba( 127, 255, 255, 0.75 );
}
button:hover {
background-color: rgba( 127, 255, 255, 0.5 )
}
button:active {
background-color: rgba( 127, 255, 255, 0.75 )
}复制代码
首先将选择栏绝对定位到窗口底部50px处,这里注意z-index: 100,将其层级设置为最高可以防止hover,click事件被其它元素拦截。然后清除button默认样式,并给它增加了:hover和:active伪类,使交互更生动。
效果如下:
然后是118个DOM元素的结构和样式,因为他们是在JavaScript代码中动态创建了,这里我单独写了一个元素的结构。
<div class="element">
<div class="number">1</div>
<div class="symbol">H</div>
<div class="detail">Hydrogen<br>1.00794</div>
</div>复制代码
CSS样式
.element {
width: 120px;
height: 160px;
cursor: default;
text-align: center;
border: 1px solid rgba( 127, 255, 255, 0.25 );
box-shadow: 0 0 12px rgba( 0, 255, 255, 0.5 );
}
.element:hover{
border: 1px solid rgba( 127, 255, 255, 0.75 );
box-shadow: 0 0 12px rgba( 0, 255, 255, 0.75 );
}
.element .number {
position: absolute;
top: 20px;
right: 20px;
font-size: 12px;
color: rgba( 127, 255, 255, 0.75 );
}
.element .symbol {
position: absolute;
top: 40px;
left: 0px;
right: 0;
font-size: 60px;
font-weight: bold;
color: rgba( 255, 255, 255, 0.75 );
text-shadow: 0 0 10px rgba( 0, 255, 255, 0.95 );
}
.element .det