满天星
思路写注释里了,没有废话,上代码
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 800px;
/* 设置视距 */
perspective: 800px;
/* 添加相对定位 */
position: relative;
}
</style>
<script>
window.onload = function () {
var head = document.querySelector("head");
var styleArray = [];
//创建事一百五十个动画
for (let i = 0; i < 150; i++) { //创建两种不同形态的五角星
if (i % 2 == 0) {
//使五角星从10px到1000px上下移动,顺时针旋转,大小缩放从1.2倍到0~1随机倍数,沿Y轴旋转一周
styleArray.push("@keyframes starRotate" + i +
" {\n0% {transform: translateY(10px) rotate(0deg) scale(1.2); " +
"}\n100% {transform: translateY(1000px) rotate(360deg) " + "scale(" + Math.random()
.toFixed(1) + ")" + " rotateX(360deg);}}\n");
} else {
//使五角星从10px到1000px上下移动,逆时针旋转,大小缩放从1.2倍到0~1随机倍数,沿Y轴旋转一周
styleArray.push("@keyframes starRotate" + i +
" {\n0% {transform: translateY(10px) rotate(360deg) scale(1.2);" +
"}\n100% {transform: translateY(1000px) rotate(0deg) " + "scale(" + Math.random()
.toFixed(1) + ")" + " rotateY(360deg);}}\n");
}
}
var styleNode = document.querySelector("style");
styleNode.innerHTML += styleArray.join('\n'); //把数组转为字符串以换行隔开
head.appendChild(styleNode);
//创建事一百五十个星星,对应一百五十个
for (let i = 0; i < 150; i++) {
var img = document.createElement("img");
document.body.appendChild(img);
img.style.position = "absolute"; //添加绝对定位
img.style.transformStyle = "preserve-3d"; //开启3d
img.style.left = "" + (Math.random() * Math.ceil(document.body.offsetWidth + "")) + "px";
img.src = "无标题.png"; //你的图片路径
img.style.width = "50px";
img.style.height = "50px";
img.style.top = "-50px";
img.style.animation = "starRotate" + i + " " + Math.ceil(Math.random() * (20 - 10 + 1) + 10) +
"s linear infinite";
}
}
</script>
</head>
<body>
</body>
</html>
效果如图: