Skip to content

Instantly share code, notes, and snippets.

@Mr-Gholam
Created April 16, 2023 14:06
Show Gist options
  • Save Mr-Gholam/ccf0979031668a8389820cf233e92950 to your computer and use it in GitHub Desktop.
Save Mr-Gholam/ccf0979031668a8389820cf233e92950 to your computer and use it in GitHub Desktop.
Mouse tracer (canvas + typescript)
export const mouseTracer = (canvas: HTMLCanvasElement, window: Window, dotColor: string, lineColor?: string) => {
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particlesArray: {
x: number;
y: number;
update(): unknown;
draw(): unknown;
size: number;
}[] = [];
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
canvas.addEventListener('click', (event) => {
for (let i = 0; i < 10; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
particlesArray.push(new Particle(event.pageX, event.layerY));
}
});
canvas.addEventListener('mousemove', (event) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
particlesArray.push(new Particle(event.pageX, event.layerY));
});
class Particle {
x: number;
y: number;
size: number;
speedX: number;
speedY: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw() {
if (!ctx) return console.log('ctx not found');
ctx.fillStyle = dotColor;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
function handleParticles() {
for (let index = 0; index < particlesArray.length; index++) {
particlesArray[index].update();
particlesArray[index].draw();
for (let extra = index; extra < particlesArray.length; extra++) {
const xDistance = particlesArray[index].x - particlesArray[extra].x;
const yDistance = particlesArray[index].y - particlesArray[extra].y;
const distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);
if (distance < 100) {
if (!ctx) return console.log('ctx not found');
ctx.beginPath();
ctx.strokeStyle = lineColor ? lineColor : dotColor;
ctx.lineWidth = particlesArray[index].size;
ctx.moveTo(particlesArray[index].x, particlesArray[index].y);
ctx.lineTo(particlesArray[extra].x, particlesArray[extra].y);
ctx.stroke();
}
}
if (particlesArray[index].size <= 0.3) {
particlesArray.splice(index, 1);
index--;
}
}
}
function animation() {
ctx?.clearRect(0, 0, canvas.width, canvas.height);
handleParticles();
requestAnimationFrame(animation);
}
animation();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment