一个旋转的立体星环(类似于摩天轮)文字效果,我们将使用HTML、CSS和JavaScript来实现这个效果。
主要组成部分
HTML部分
- 没有额外的HTML元素,所有内容通过JavaScript动态生成。
CSS部分
- 设置了基本的样式,包括背景颜色为浅灰色 (
#f4f4f9)。 - 定义了文字的基本样式,包括字体大小为
24px,加粗,并且居中对齐。
JavaScript部分
- 使用一个预定义的鲜艳颜色数组来生成随机颜色。
- 创建文字元素,并将其添加到页面中。
- 更新每个文字的位置,使其围绕鼠标形成一个旋转的文字环。
- 生成初始的文字元素。
- 初始化文字元素,并监听鼠标移动事件以更新鼠标位置。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>立体文字环效果</title>
<style>
body {
margin: 0;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
.text-star {
position: absolute;
font-size: 24px;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<script>
const numStars = 20;
const textStars = [];
const radius = 130; // 文字环半径
const angleStep = (Math.PI * 2) / numStars; // 每个文字的角度间隔
function getRandomColor() {
const colors = [
'#FF5733', '#33FF57', '#3357FF', '#F3FF33', '#FF33A1',
'#33FFF6', '#F633FF', '#33F6FF', '#FFB333', '#FF33C6'
];
return colors[Math.floor(Math.random() * colors.length)];
}
function createTextStar(text, x, y) {
const textStar = document.createElement('div');
textStar.className = 'text-star';
textStar.textContent = text;
textStar.style.color = getRandomColor(); // 设置随机鲜艳颜色
textStar.style.left = `${x - 12}px`; // 调整文字位置使其居中
textStar.style.top = `${y - 12}px`; // 调整文字位置使其居中
document.body.appendChild(textStar);
textStars.push({ element: textStar, x, y });
}
function animate(mouseX, mouseY) {
for (let i = 0; i < textStars.length; i++) {
const angle = angleStep * i + performance.now() / 1000; // 添加时间因素使文字环旋转
const x = mouseX + radius * Math.cos(angle);
const y = mouseY + radius * Math.sin(angle);
textStars[i].element.style.left = `${x - 12}px`; // 调整文字位置使其居中
textStars[i].element.style.top = `${y - 12}px`; // 调整文字位置使其居中
}
requestAnimationFrame(() => animate(mouseX, mouseY));
}
function spawnTextStars(num) {
const text = "网页特效库";
for (let i = 0; i < num; i++) {
const angle = angleStep * i;
const x = window.innerWidth / 2 + radius * Math.cos(angle);
const y = window.innerHeight / 2 + radius * Math.sin(angle);
createTextStar(text[Math.floor(i % text.length)], x, y);
}
}
spawnTextStars(numStars);
let mouseX = window.innerWidth / 2;
let mouseY = window.innerHeight / 2;
document.addEventListener('mousemove', (event) => {
mouseX = event.clientX;
mouseY = event.clientY;
});
animate(mouseX, mouseY);
</script>
</body>
</html>

No responses yet