当前位置: 首页 > 工具软件 > Rotating 3D > 使用案例 >

Web初学者--作业4-[3D旋转的动态效果]

毛正浩
2023-12-01

1.项目介绍

这是一个简单的,3D旋转效果图,纯属html+css+JS动画而成,可以给喜欢的人表白哦~~

效果图如下:

Happy Birthday

2.项目分析

(1)html里写上基础的div标签就可以啦

(2)css样式里,添加:root,简单设置一下视觉距离,再给添加上动画和反向动画

(3)JS里,添加自己想要看到的词语,获取各自元素节点之后,对之进行DOM操作就可以啦

(具体可以看下面代码哦~~)

3.代码部分

A:html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Happy Birthday</title>
  <link rel="stylesheet" href="./index.css">
</head>
<body>
  <div class="contanier"></div>
  <script src="./index.js"></script>
</body>
</html>

B:css

*{
  margin: 0;
  padding: 0;
}
:root{
  /* 上外边距 */
  --margin-top:0;
  /* 左外边距 */
  --margin-left:0;
  /* 动画时长 */
  --animation-duration: 0s;
  /* 动画延迟时间 */
  --animation-delay: 0;
}
body{
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #111;
  overflow: hidden;
  /* 设置视觉距离 */
  perspective: 1300px;
}
div{
  transform-style: preserve-3d;
}
.word-box,
.word-box .word{
  position: absolute;
  animation: rotY 0s linear infinite ;
  animation-duration: var(--animation-duration);
  animation-delay: var(--animation-delay);
}
.word-box{
  margin-top: var(--margin-top);
}
.word-box .word{
  margin-left: var(--margin-left);
}
.word-box .word{
  /* 反向动画 */
  animation-duration: reverse;
}
/* 定义动画 */
@keyframes rotY{
  to{
    /* 1turn一圈 */
    transform: rotateY(1turn);
  }
}

C:JS

var words = [
  '生日快乐',
  '生日快乐',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '生日快乐',
  '小宝贝',
  '生日快乐',
  '生日快乐',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',
  '我爱你',
  '小宝贝',
  '生日快乐',
  '我爱你',

];
function randomNum(min,max) {
  var num = (Math.random()*(max-min+1)+min).toFixed(2);
  return num;
}
function init() {
  var container = document.querySelector(".contanier");
  var f = document.createDocumentFragment();//创建文档片段对象

  words.forEach(w =>{
    var word_box = document.createElement('div');
    var word = document.createElement('div');

    word.innerText = w;
    word.classList.add('word');

    // 随机生成色相知(0红色,120绿色,360红色)
    var hue = randomNum(0,240);
    word.style.color = 'hsl('+hue+',100%,65%)';

    word_box.classList.add("word-box");
    // 生成随机数值,并赋值给自定义属性
    word_box.style.setProperty("--margin-top",randomNum(-40,20)+'vh');
    word_box.style.setProperty("--margin-left",randomNum(6,35)+'vw');
    word_box.style.setProperty("--animation-duration",randomNum(8,20)+'s');
    word_box.style.setProperty("--animation-delay",randomNum(-20,0)+'s');

    word_box.appendChild(word);
    f.appendChild(word_box);


  })
  container.appendChild(f);
}
// 绑定加载事件
window.addEventListener('load',init);

 类似资料: