CSS3D实现立方体

vue代码

<template>
  <div style="height: 100%;display: flex;justify-content: center;align-items: center;" class="no-select">
    <el-button @click="resetDiv">重置动画</el-button>
    <div class="camera" @click="rotateHandle">
      <div v-if="resetFlag" id="stage" class="stage">
        <div class="cube up">up</div>
        <div class="cube down">down</div>
        <div class="cube left">left</div>
        <div class="cube right">right</div>
        <div class="cube front">front</div>
        <div class="cube back">back</div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: 'HomeIndex',
  data() {
    return {
      rotateFlag: true,
      resetFlag: true
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    // 点击开始或暂停动画
    rotateHandle() {
      const target = document.getElementById("stage")
      target.style.animationPlayState = this.rotateFlag ? 'running' : 'paused'
      this.rotateFlag = !this.rotateFlag
    },
    // 点击重置动画
    resetDiv() {
      this.resetFlag = false
      // 挂载完成后,设置重新渲指定dom
      this.$nextTick(() => this.resetFlag = true)
    }
  }
}
</script>

CSS样式

<style scoped>
.camera {
  width: 600px;
  height: 600px;
  border: 2px solid black;
  background-color: bisque;
  /*在场景上设置视角*/
  perspective: 3000px;
  /*改变 3D 元素的底部位置。*/
  perspective-origin: -100% -100%;
  overflow: hidden;
}

.stage {
  position: relative;
  border: 2px solid black;
  background-color: #abebfd;
  top: 10%;
  left: 10%;
  width: 80%;
  height: 80%;
  /*元素的子元素是位于 3D 空间中*/
  transform-style: preserve-3d;
  animation: test 8s linear infinite paused;
}
/* 立方体水平旋转、和垂直旋转 */
@keyframes test {
  from {
    transform: rotateX(0deg) rotateY(0deg);
  }
  50% {
    transform: rotateX(-360deg) rotateY(0deg);
  }
  to {
    transform: rotateX(-360deg) rotateY(360deg);
  }
}

/* 立方体每个面的基本样式,位置、大小、字体、背景 */
.cube {
  position: absolute;
  top: 25%;
  left: 25%;
  width: 200px;
  height: 200px;
  background-color: #00BFFF;
  color: black;
  opacity: 0.5;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: transform 1s;
}

/* 上面:X轴顺时针旋转90度,Y轴向上平移100px */
.up {
  transform: translateY(-100px) rotateX(90deg);
}

/* 下面:X轴逆时针旋转90度,Y轴向下平移100px */
.down {
  transform: translateY(100px) rotateX(-90deg);
}

/* 左面:Y轴顺时针旋转90度,X轴向左平移100px */
.left {
  transform: translateX(-100px) rotateY(-90deg);
}

/* 右面:Y轴逆时针旋转90度,X轴向左平移100px */
.right {
  transform: translateX(100px) rotateY(90deg);
}
/* 前面:Z轴向前平移100px */
.front {
  transform: translateZ(100px);
}
/* 后面:Y轴逆时针旋转180度,Z轴向后平移100px */
.back {
  transform: translateZ(-100px) rotateY(180deg);
}
</style>

最终效果

css3D立方体

说明:点击外层div开始或暂停旋转动画,点击按钮重置动画

posted @ 2023-12-26 09:37  喵师傅  阅读(92)  评论(0编辑  收藏  举报