26. Tracking the cursor
You’re not limited to Framer’s events; you can also use common events (in React: synthetic events) like, for example, onMouseMove()
.
Code component
This one is comparable to Drag: 3D transform. Here, we’re also tracking x
and y
movements with Motion values, only this time, not directly.
We have x
and y
Motion values, but they’re not connected to any element. Instead, they are updated using set()
in the handleMouse()
event handler triggered by the background’s onMouseMove()
event (an HTML event).
set()
SyntheticEvent, UI Events
onMouseMove()
The x
and y
Motion values are then transformed to rotateX
and rotateY
3D rotation values, which we pass to the box in the center.
Here, the same happens as in the earlier example:
x
changes the y-rotation:rotateY
,- and
y
changes the x-rotation:rotateX
.
Also, the background got a bit of perspective
because otherwise, you wouldn’t see any 3D effect.
CodeSandbox
The version in the CodeSandbox is a bit different because we can’t know the position of the div in the background up front.
Here, we grab the currentTarget
from the event, use getBoundingClientRect()
to get the div’s position (from the left
and top
), and then detract those from the absolute position of the pointer (clientX
and clientY
) to get the pointer’s position inside the div.
Code overrides
Actually, we don’t have to use Motion values; we can also save the pointer’s position in a state, or here: a CreateStore()
data store.
Also, since we’re not using Motion values, we use transform()
instead of useTransform()
to change them.