Canvas Particle & Meteor Effects Tutorial
To achieve cool particle and meteor effects, you can use Canvas to draw animations. Here is a simple example code to achieve this effect:
- Create an HTML document and add a Canvas element to it.
<canvas id="canvas" width="800" height="600"></canvas>
- Write code in Javascript to achieve particle and meteor effects.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let particles = [];
function createParticles() {
for (let i = 0; i < 100; i++) {
let particle = {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
speedX: Math.random() * 4 - 2,
speedY: Math.random() * 4 - 2,
color: 'white',
size: Math.random() * 3 + 1
};
particles.push(particle);
}
}
function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
let particle = particles[i];
ctx.fillStyle = particle.color;
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fill();
particle.x += particle.speedX;
particle.y += particle.speedY;
if (particle.x > canvas.width || particle.x < 0) {
particle.speedX *= -1;
}
if (particle.y > canvas.height || particle.y < 0) {
particle.speedY *= -1;
}
}
}
function createMeteor() {
let meteor = {
x: Math.random() * canvas.width,
y: 0,
speedY: Math.random() * 4 + 2,
color: 'red',
size: Math.random() * 5 + 2
};
particles.push(meteor);
}
function draw() {
createParticles();
setInterval(() => {
createMeteor();
}, 3000);
setInterval(() => {
drawParticles();
}, 1000 / 60);
}
draw();
The above code will draw 100 white particles on the Canvas and generate a red shooting star at the top every 3 seconds. By controlling the speed and position of the particles, different effects can be achieved. You can adjust the parameters in the code to create cooler effects as needed.