Cursor · 21 of 22
Particle Sparks
Canvas particles burst from cursor
<div class="sparks-area" id="sparksArea">
<h2>Sparks</h2>
<canvas class="sparks-canvas" id="sparksCanvas"></canvas>
</div>
.sparks-area {
position: relative;
height: 240px;
display: flex;
align-items: center;
justify-content: center;
background: #12121a;
overflow: hidden;
font-family: sans-serif;
}
.sparks-area h2 { color: #333; }
.sparks-canvas {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
pointer-events: none;
}
var area = document.getElementById('sparksArea');
var canvas = document.getElementById('sparksCanvas');
var ctx = canvas.getContext('2d');
var SPAWN = 3; // particles per mousemove event
var GRAVITY = 0.05;
var DECAY = 0.02; // life lost per frame
var particles = [];
function resize() {
canvas.width = area.clientWidth;
canvas.height = area.clientHeight;
}
resize();
window.addEventListener('resize', resize);
area.addEventListener('mousemove', function (e) {
var rect = area.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
for (var i = 0; i < SPAWN; i++) {
particles.push({
x: x,
y: y,
vx: (Math.random() - 0.5) * 4,
vy: (Math.random() - 0.5) * 4 - 1,
life: 1,
size: 1 + Math.random() * 2.5,
hue: 255 + Math.random() * 40 // purple range
});
}
});
function tick() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles = particles.filter(function (p) { return p.life > 0; });
particles.forEach(function (p) {
p.x += p.vx;
p.y += p.vy;
p.vy += GRAVITY;
p.life -= DECAY;
if (p.life <= 0) return; // negative radius would throw
ctx.globalAlpha = p.life;
ctx.fillStyle = 'hsl(' + p.hue + ', 90%, 70%)';
ctx.beginPath();
ctx.arc(p.x, p.y, Math.max(0, p.size * p.life), 0, Math.PI * 2);
ctx.fill();
});
ctx.globalAlpha = 1;
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);