Proton
Proton copied to clipboard
Here is an elegant example combining React, TypeScript, and Proton.
Here is an example that combines React, TypeScript, and Proton, adhering to the principles of faithfulness, expressiveness, and elegance.
import React, { useEffect, useRef } from 'react';
import Proton, {
Emitter,
Rate,
Span,
Mass,
Radius,
Life,
Velocity,
Alpha,
Scale,
Color,
CanvasRenderer,
} from 'proton-engine';
const MouseFollower: React.FC = () => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const protonRef = useRef<Proton | null>(null);
const emitterRef = useRef<Emitter | null>(null);
const rendererRef = useRef<CanvasRenderer | null>(null);
useEffect(() => {
const proton: Proton = new Proton();
protonRef.current = proton;
const emitter: Emitter = new Emitter();
emitter.rate = new Rate(new Span(5, 10), new Span(0.1, 0.25));
emitter.addInitialize(new Mass(1));
emitter.addInitialize(new Radius(2, 10));
emitter.addInitialize(new Life(1, 3));
emitter.addInitialize(new Velocity(new Span(0.5, 1.5), new Span(0, 360), 'polar'));
emitter.addBehaviour(new Alpha(1, 0));
emitter.addBehaviour(new Scale(1, 0));
emitter.addBehaviour(new Color(['#FF0000', '#FFFF00', '#00FF00', '#0000FF']));
proton.addEmitter(emitter);
emitterRef.current = emitter;
const canvas: HTMLCanvasElement = canvasRef.current!;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const renderer: CanvasRenderer = new CanvasRenderer(canvas);
proton.addRenderer(renderer);
rendererRef.current = renderer;
const animate = (): void => {
requestAnimationFrame(animate);
proton.update();
};
emitter.emit();
animate();
return () => {
emitter.stop();
proton.destroy();
};
}, []);
const handleMouseMove = (event: React.MouseEvent<HTMLCanvasElement>): void => {
if (emitterRef.current) {
emitterRef.current.p.x = event.clientX;
emitterRef.current.p.y = event.clientY;
}
};
return <canvas ref={canvasRef} onMouseMove={handleMouseMove} />;
};
export default MouseFollower;