Export Image
Export Code

Mouse Follower

Ian Johnson

Last edited Jul 08, 2020
Created on Jul 08, 2020

A program that follows your mouse with a circle.


Tutorials:


Extras:

  • As the circle is moved around the SVG, a Path is drawn that traces it's route (Thanks to Curran for the live help with this!)
  • Button added which removes the trace path and allows the user to re-draw it.

Uni-directional Data Flow Process:

  • -> RENDER
  • -> Perception & Cognition - User processes & understands what they see
  • -> Volition & Action - User wants to do something to change what they see
  • -> INTERACTION
  • -> Event Listener(s) are triggered for the particular event the user wants to change
  • -> Change State
  • -> RE-RENDER - VirtualDOM reconciliation - only updates what changed

Notes:

  1. initialMousePosition = object that puts the circle in the centre of the SVG (passed in below) (render).
  2. Create useState variable and function (mousePosition & setMousePosition). On the initial render, mousePosition = initialMousePosition.
  3. Mouse position initialises x and y co-ordinates.
  4. onMouseMove = interaction, initialised on first render, triggers function on state change (enables interaction).
  5. Changes the state of the circle based on the interaction (X & Y position). It extracts clientX & clientY from onMouseMove (many more look to be available) (interaction).
  6. Destructure to get each new coordinate.
  7. New state object defined and assigned to setMousePosition (see 9. for a better way).
  8. setMousePosition makes App re-render with the new object values as mousePosition.
  9. useCallback hook wrapped into handleMouseMove with a second argument as an array of the most recent dependencies. This means it doesn't reset the handleMouseMove as a new function each render. Only the first time it's rendered, so it's more efficient.
MIT Licensed