こんにちは。茨城県水戸市でホームページ制作をしています、レターズです。
今日は、ある案件で画面上に紙吹雪を実装しましたのでそのコードをご紹介します。
自分で作ったオリジナルの画像をランダムに選んで降らすことができます。
いきなりですが下記がそのコードです。
<body>
<canvas id="canvas"></canvas>
</body>
// Particle class
class Particle {
constructor(x, y, size, speed, imageSrc) {
this.x = x;
this.y = y;
this.size = size;
this.speed = speed;
this.image = new Image();
this.image.src = imageSrc;
this.directionX = Math.random() < 0.5 ? -1 : 1;
this.rotationSpeed = (Math.random() * 0.04) - 0.02;
this.rotationAngle = Math.random() * Math.PI * 2;
}
// Update particle position and behavior
update() {
this.y += this.speed;
this.x += this.directionX * (Math.random() * 2);
if (this.y > canvas.height) {
this.y = 0;
this.x = Math.random() * canvas.width;
}
this.rotationAngle += this.rotationSpeed;
}
// Draw particle on canvas
draw(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotationAngle);
// Set shadow properties
ctx.shadowColor = "#000";
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
// Draw image with shadow
ctx.drawImage(this.image, -this.size / 2, -this.size / 2, this.size, this.size);
ctx.restore();
}
}
// Create canvas element
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Array of image sources
const imageSources = [
//change image path to whereever you put images in
"path/to/image1.png",
"path/to/image2.png",
"path/to/image3.png",
// Add more image sources as needed
];
// Create an array to store particles
const particles = [];
// Create particles
for (let i = 0; i < 100; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const size = Math.random() * 20 + 10;
const speed = Math.random() * 2 + 1;
const imageSrc = imageSources[Math.floor(Math.random() * imageSources.length)];
particles.push(new Particle(x, y, size, speed, imageSrc));
}
// Animation loop
function animate() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update and draw particles
particles.forEach((particle) => {
particle.update();
particle.draw(ctx);
});
// Request next frame
requestAnimationFrame(animate);
}
// Start animation
animate();