If you want to Create a Rain Effect in HTML 5 with Javascript and CSS, then you can follow these:
HTML;
<!DOCTYPE html>
Rain Effect Example
CSS (style.css):
body {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
}
JavaScript (rain.js):
// Set up the canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Set up the raindrops
var drops = [];
for (var i = 0; i < 50; i++) {
drops.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
speed: 2 + Math.random() * 3,
length: 5 + Math.random() * 10
});
}
// Draw the raindrops
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#2F4F4F';
for (var i = 0; i < drops.length; i++) {
var drop = drops[i];
ctx.fillRect(drop.x, drop.y, 2, drop.length);
drop.y += drop.speed;
if (drop.y > canvas.height) {
drop.y = -drop.length;
}
}
}
// Update the raindrops every frame
function update() {
draw();
requestAnimationFrame(update);
}
update();
In this example, I use the HTML canvas element to draw the raindrops on the screen, and I use JavaScript to update the position of the raindrops every frame. I also use CSS to set the canvas to take up the entire screen and to hide any overflow outside the canvas.
The raindrops are represented as an array of objects, each with x and y coordinates, a speed, and a length. We use a loop to draw each raindrop as a rectangle with a fixed width of 2 and a variable length based on the drop's length property. We then update the position of each drop by adding the speed to its y coordinate and checking if it has gone off the bottom of the screen, in which case we reset its y coordinate to the top of the screen.I've used these steps on nerfweb, It looks really cool
I use requestAnimationFrame to update the raindrops every frame and create a smooth animation.
Top comments (0)