Mouse Follower
✓ Published0🌍 Public
A circular marker follows the mouse cursor across an SVG canvas, while a path traces the complete route of its movement. The visualization demonstrates unidirectional data flow in React with D3.js v5, using React state and Hooks (`useState`, `useCallback`) to handle mouse events and trigger re-renders. The path is built by collecting `clientX` and `clientY` coordinates on each `onMouseMove` event, and a reset button clears the trace back to the current cursor position. The SVG is rendered directly via React, with D3 providing the `path` utility for constructing the line string.
AI-generated descriptionA 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:
- 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.
MIT Licensed