Events - Mouse

Effects can listen to the user's mouse position over the component (or the effect layer in a later version). To listen to the mouse you should call listenMouse() on the effect after initialisation.

import Effect from './MyNeonEffect';
const effect = new Effect();
effect.listenMouse();

Once the effect is listening to the mouse the users' mouse position will be available in the effect as a 2D array called this.mouse. The first array value is the x position, the second is the y position.

Using these values you can draw things where the user's mouse is. Using the example effect that you if you followed Create An Effect you can replace the x and y values with this.mouse to draw the circle under the mouse.

import { Fx } from 'react-neon';

export default class MyNeonEffect extends Fx {
    draw() {
      // If we have a canvas to draw on...
      if (this.ctx!==null) {
        // Clear the canvas
        this.ctx.clearRect(0, 0, this.bb.width, this.bb.height);

        // Set the fill style to opaque white
        this.ctx.fillStyle = 'hsla(0,100%,100%,1)';

        // Draw a circle
        this.ctx.beginPath();
        this.ctx.arc(this.mouse[0], this.mouse[1], 50, 0, 2 * Math.PI);
        this.ctx.fill();

      }
      // Call the next frame
      this.raf = requestAnimationFrame(this.draw);
    }
}

This gives us an effect like this. (Move your mouse over the effect to see it properly.)

Mouse Position History

Sometimes a single mouse position isn't enough, and you want to get the history of the previous positions too. Neon gives you that functionality by enabling listenMouseHistory() and then you can use the this.history array in your effect.

import Effect from './MyNeonEffect';
const effect = new Effect();
effect.listenMouseHistory();

The history is an array of mouse positions in the same format as this.mouse, [x, y].

import { Fx } from 'react-neon';

export default class MyHistoryEffect extends Fx {
    draw() {
      // If we have a canvas to draw on...
      if (this.ctx!==null) {
        // Clear the canvas
        this.ctx.clearRect(0, 0, this.bb.width, this.bb.height);

        // Set the fill style to opaque white
        this.ctx.fillStyle = 'hsla(0,100%,100%,0.25)';

        // Draw a circle
        if (this.history.length > 0) {
          this.history.forEach((pos) => {
            this.ctx.beginPath();
            this.ctx.arc(pos[0], pos[1], 20, 0, 2 * Math.PI);
            this.ctx.fill();
          })
        }
        
      }
      // Call the next frame
      this.raf = requestAnimationFrame(this.draw);
    }
}

Now the previous positions will be drawn as well.

Neon currently tracks the mouse forever, so the history array will fill up fast. It's worthwhile checking the length and trimming it if it gets too big, or your effect will eventually slow down a lot.