Export Image
Export Code

Mouse Follower & Path Drawer

Tom-S82

Last edited Jul 09, 2020
Created on Jul 08, 2020
Forked from Smiley Face Part 1

A program that follows your mouse with a circle & draws it's path.

(click the SVG to remove the path trace)


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!)
  • An onClick function has been added to the SVG. This removes the trace path and allows the user to re-draw it.
  • Styling has been added to the circle and the path.

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.

  1. initialMousePath sets the initial co-ordinates of the path as M x y.
  2. Create useState variable and function (mousePath & setMousePath). Same logic as (2).
  3. Current co-ordinates are grabbed and appended to the path as L x y (e.g. M x y L x y L x y)
  4. Button calls ResetPath callback
  5. Mouse path is reset to M x y. This clears the old path.
MIT Licensed