利用html5和css3制作旋转木马效果图

546 阅读1分钟

本文由六张图片通过transform、perspective和rotate等样式来实现轮播的效果。

%HI_2T`5~PUUP7_GONFRJMG.png

  1. 首先设置六个div并设置好样式。 <body> <section> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </section> </body>

    section {
         position: relative;
         width: 300px;
         height: 200px;
         margin: 100px auto;
     }
    
     section div {
         position: absolute;
         top: 0;
         left: 0;
         width: 100%;
         height: 100%;
         background: url(../3d/dog.jpeg);
         background-size: cover;
     }
    

2.添加透视实现近大远小的效果。

body { perspective: 1000px; /* 这个透视可做用于section,也能作用于section里面的孩子 */ }

  1. 然后由于一共有6个盒子和360°的角度,因此每个盒子沿着Y轴一次旋转,每次递增60°,围成一圈。

    section div:nth-child(1) {
         transform: translateZ(300px);
     }
    
     section div:nth-child(2) {
         transform: rotateY(60deg) translateZ(300px);
         /* 先旋转再移动 :这种写法,代表每个盒子的坐标轴各不一样,旋转的时候坐标轴的方向也跟着旋转。 */
     }
    
     section div:nth-child(3) {
         transform: rotateY(120deg) translateZ(300px);
     }
    
     section div:nth-child(4) {
         transform: rotateY(180deg) translateZ(300px);
     }
    
     section div:nth-child(5) {
         transform: rotateY(240deg) translateZ(300px);
     }
    
     section div:nth-child(6) {
         transform: rotateY(300deg) translateZ(300px);
     }
     
    

    4.保持3d效果

         section {
    
         position: relative;
         width: 300px;
         height: 200px;
         margin: 100px auto;
         transform-style: preserve-3d;
     }
     
    

    5.添加动画效果并调用,并且鼠标悬停时停止旋转。

          section {
    
         position: relative;
         width: 300px;
         height: 200px;
         margin: 100px auto;
         transform-style: preserve-3d;
         /* 调用动画效果实现自动播放,无限线性循环 */
         animation: rotate 5s linear infinite;
    
     }
    
     /* 动画效果 */
     @keyframes rotate {
         0% {
             transform: rotateY(0);
         }
    
         100% {
             transform: rotateY(360deg);
         }
     }
    
     /* 鼠标悬停时动画停止 */
     section:hover {
         animation-play-state: paused;
     }