利用CSS3的新增属性,实现简单的3D多棱柱旋转效果,并且将多棱柱的生成写成函数,这样就可以随意生成多棱柱了。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
/*n边形的外角和为360 360/n
n变形的内角 180 - 360/n*/
*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
overflow: hidden;
}
#wrap{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 300px;
height: 300px;
/*border: 1px solid;*/
perspective: 1000px;
}
#wrap > .box{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 300px;
height: 300px;
transition:10s transform;
transform-style: preserve-3d;
/*transform-origin: center center -28.867513459481287px;*/
}
#wrap > .box > div{
position: absolute;
width: 300px;
height: 300px;
background: pink;
text-align: center;
font: 50px/300px "微软雅黑";
/*transform-origin: center center -28.867513459481287px;*/
backface-visibility: hidden;
}
/*#wrap > .box > div:nth-child(3){
transform: rotateY(240deg);
}
#wrap > .box > div:nth-child(2){
transform: rotateY(120deg);
}
#wrap > .box > div:nth-child(1){
}*/
#wrap:hover > .box{
transform: rotateY(360DEG);
}
</style>
</head>
<body>
<div id="wrap">
<div class="box">
</div>
</div>
</body>
<script type="text/javascript">
//n:棱数
window.onload=function(){
createLZ(10);
}
function createLZ(n){
var boxNode = document.querySelector("#wrap > .box");
var stlyleNode = document.createElement("style");
//外角
var degOut = 360/n;
//内角
var degIn = 180 - 360/n;
var text = "";
var cssText = "";
for(var i=0;i<n;i++){
text+="<div>"+(i+1)+"</div>";
cssText+="#wrap > .box > div:nth-child("+(i+1)+"){transform: rotateY("+(i*degOut)+"deg);}";
}
boxNode.innerHTML=text;
var mianNode = document.querySelector("#wrap > .box > div");
//棱长
var length = mianNode.offsetWidth;
cssText+="#wrap > .box{transform-origin: center center -"+(length/2 * Math.tan((degIn/2)*Math.PI/180))+"px;}";
cssText+="#wrap > .box > div{transform-origin: center center -"+(length/2 * Math.tan((degIn/2)*Math.PI/180))+"px;}";
stlyleNode.innerHTML=cssText;
document.head.appendChild(stlyleNode);
}
</script>
</html>