【JS+H5+CSS实现烟花特效】
以下是一个简单的烟花特效实现的代码示例:
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #111;
}
.confetti {
--size-min: 1px;
--size-max: 6px;
--speed-min: 0.5s;
--speed-max: 2s;
--density: 2000;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
animation: confetti-animation linear infinite;
}
@keyframes confetti-animation {
0% {
transform: translate3d(0, 0, 0);
}
100% {
transform: translate3d(
calc(
(var(--size-max) - var(--size-min)) *
(random() - 0.5) * 2 + var(--size-min)
),
calc(
(var(--size-max) - var(--size-min)) *
(random() - 0.5) * 2 + var(--size-min) +
var(--size-max) * 2
),
0
);
opacity: 0;
}
}
</style>
</head>
<body>
<div class="confetti" style="--size-min: 2px; --size-max: 4px; --speed-min: 0.2s; --speed-max: 1s; --density: 5000;"></div>
<script>
const confetti = document.querySelector('.confetti');
const random = (min, max) => Math.random() * (max - min) + min;
const range = (min, max) => new Array(max - min + 1).fill(min).map((n, i) => n + i);
const createConfetti = () => {
const size = `${random(2, 6)}px`; // min and max size
const speed = `${random(0.5, 2)}s`; // min and max animation duration
const style = `
width: ${size};
height: ${size};
background: rgba(255, 255, 255, ${random(0.2, 0.8)});
animation-duration: ${speed};
animation-delay: ${random(0, 10)}s;
`;
return `<div style="${style}"></div>`;
};
const density = confetti.style['--density'];
const confettiCount = document.querySelectorAll('.confetti div').length;
if (confettiCount < density) {
const confettiFragments = range(density - confettiCount).map(createConfetti).join('');
confetti.insertAdjacentHTML('beforeend', confettiFragments);
}
</script>
</body>
</html>
这段代码会在页面上
评论已关闭