Mouse Follower & Path Drawer
✓ Published3🌍 Public
This example demonstrates a reactive mouse-follower interaction in a React-powered SVG visualization. A gradient-filled circle tracks the cursor's movement, while a d3 path element dynamically appends line segments to record the cursor’s trajectory. The path uses an SVG linear gradient, and the circle uses a radial gradient, both defined in defs. Clicking the SVG triggers a state reset via a callback, clearing the drawn path and allowing a new trace to begin. The visualization leverages React’s `useState` and `useCallback` hooks for efficient state management and rendering updates.
AI-generated descriptionA 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:
- initialMousePosition = object that puts the circle in the centre of the SVG (passed in below) (render).
- Create useState variable and function (mousePosition & setMousePosition). On the initial render, mousePosition = initialMousePosition.
- Mouse position initialises x and y co-ordinates.
- onMouseMove = interaction, initialised on first render, triggers function on state change (enables interaction).
- 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).
- Destructure to get each new coordinate.
- New state object defined and assigned to setMousePosition (see 9). for a better way).
- setMousePosition makes App re-render with the new object values as mousePosition.
- 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.
- initialMousePath sets the initial co-ordinates of the path as M x y.
- Create useState variable and function (mousePath & setMousePath). Same logic as (2).
- 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)
- Button calls ResetPath callback
- Mouse path is reset to M x y. This clears the old path.
MIT Licensed