《JavaScript》ランダムで2色の紙吹雪を降らせる
公開日:2025年02月19日 最終更新日:2025年2月19日
2色の四角を回転させながらを降らせています。
DEMO
わかりやすいように、別ページにDEMOを用意しました。
HTML
JavaScriptで要素を生成しているので、<body>以外は特に表記は必要ありません。
<body></body>
CSS
紙吹雪の色はJavascriptで上書きしています。
body {
margin: 0;
overflow: hidden;
padding: 0;
}
.confetti {
background-color: #e5c76a;
height: 20px;
opacity: .8;
position: absolute;
transform-origin: center;
width: 20px;
}
JavaScript
紙吹雪の色、落下速度や揺れ速度は数値を変更して調整してください。
const confettiAmount = 200; // 紙吹雪の量
let confettis = [];
function createConfetti() {
for (let i = 0; i < confettiAmount; i++) {
let confetti = document.createElement("div");
confetti.classList.add("confetti");
// ランダムな初期位置、サイズ、色を設定
const leftPosition = Math.random() * window.innerWidth;
const topPosition = Math.random() * window.innerHeight;
const size = Math.random() * 10 + 10;
const colors = ["#e5c76a", "#ccb05e"]; // 紙吹雪の色
const color = colors[Math.floor(Math.random() * colors.length)];
confetti.style.left = `${leftPosition}px`;
confetti.style.top = `${topPosition}px`;
confetti.style.width = `${size}px`;
confetti.style.height = `${size}px`;
confetti.style.backgroundColor = color;
// 紙吹雪の情報を配列に格納
confettis.push({
element: confetti,
topPosition: topPosition,
leftPosition: leftPosition,
swayDirection: Math.random() < 0.5 ? 1 : -1,
swayAmount: Math.random() * 20 + 15, // 揺れ幅
speed: Math.random() * 2 + 1, // 落下速度
swaySpeed: Math.random() * 0.02 + 0.01, // 揺れ速度
rotateX: Math.random() * 360,
rotateZ: Math.random() * 360,
rotateXSpeed: Math.random() * 4 + 2, // X軸の回転速度
rotateZSpeed: Math.random() * 4 + 2 // Z軸の回転速度
});
document.body.appendChild(confetti);
}
}
function updateConfetti() {
confettis.forEach(confetti => {
// 落下
confetti.topPosition += confetti.speed;
// 左右の揺れ
const swayOffset = Math.sin(confetti.topPosition * confetti.swaySpeed) * confetti.swayAmount;
confetti.leftPosition += swayOffset * confetti.swayDirection * 0.05;
// 2軸回転(X軸&Z軸)
confetti.rotateX += confetti.rotateXSpeed;
confetti.rotateZ += confetti.rotateZSpeed;
// 更新
confetti.element.style.transform = `translate(${confetti.leftPosition}px, ${confetti.topPosition}px) rotateX(${confetti.rotateX}deg) rotateZ(${confetti.rotateZ}deg)`;
// 画面外に出たら、一番上(-20px)から再配置
if (confetti.topPosition > window.innerHeight) {
confetti.topPosition = -20; // 画面の一番上からスタート
confetti.leftPosition = Math.random() * window.innerWidth;
}
// 位置を適用
confetti.element.style.top = `${confetti.topPosition}px`;
confetti.element.style.left = `${confetti.leftPosition}px`;
});
}
// 実行
window.onload = function () {
createConfetti();
setInterval(updateConfetti, 16); // 60fps
};