To achieve this special effect, follow these steps starting from the end:
- Utilize CSS transforms like
scaleX()
and scaleY()
- Determine the cursor movement velocity in both x and y axes
- Collect necessary information to calculate velocity such as:
- Current cursor position (accessible via
MouseEvent
)
- Previous cursor position (must be stored)
- Time elapsed between previous and current mouse events
Here's how it can be implemented:
Step 1: Update your data
object to store previous XY coordinates along with timestamp
Add the following properties to your data
object:
data() {
return {
hideCursor: false,
prevX: 0,
prevY: 0,
prevTimeStamp: 0,
};
},
Step 2: Cache these values in your mousemove
callback function
Store these values at the end of your mousemove
callback after other logic:
document.addEventListener("mousemove", (e) => {
// LOGIC HERE
// Update cached values
this.prevX = e.pageX;
this.prevY = e.pageY;
this.prevTimeStamp = e.timeStamp;
});
Step 3: Calculate velocity by comparing current and previous values
Calculate velocity in X and Y axes based on the absolute difference and time elapsed:
const deltaX = Math.abs(e.pageX - this.prevX);
const deltaY = Math.abs(e.pageY - this.prevY);
const deltaTime = e.timeStamp - this.prevTimeStamp;
const velocityX = deltaX / deltaTime;
const velocityY = deltaY / deltaTime;
Step 4: Translate velocities into CSS scale transform
You can decide how to translate velocities into a CSS scale transform that suits your needs. For example:
const scaleX = 1 + velocityX / 10;
const scaleY = 1 + velocityY / 10;
cursor.style.top = `${e.pageY}px`;
cursor.style.left = `${e.pageX}px`;
cursor.style.transform = `translate(-50%, -50%) scaleX(${scaleX}) scaleY(${scaleY})`;
(Optional) Step 5: Handle the mouseout
event on the viewport
To prevent the cursor from getting stuck in an odd state when leaving the viewport:
document.addEventListener('mouseout', () => {
cursor.style.transform = 'none';
});
Check out an updated example using your CodeSandbox below:
https://codesandbox.io/s/vigorous-easley-7odl4?fontsize=14&hidenavigation=1&theme=dark