Adjustable Cursor - modify size while in motion at high speeds

I've designed a unique custom cursor and I am looking to enhance its functionality by adjusting its scale dynamically during fast movements. Similar to the cursor on this website: Example.com

Here is my custom cursor for reference: CodeSandBox

What I aim to achieve is that when the cursor moves rapidly in horizontal directions, the scaleX should increase and decrease accordingly. Similarly, for vertical movements, scaleY should expand and contract...

Edit: Challenging rotation - New Task

Congratulations to Terry for successfully tackling the previous challenge! Now, we are faced with a new obstacle. Even when moving the cursor diagonally, it must rotate in order to deliver flawless results.

Check out Terry's solution here: Terry's CodeSandbox

I propose dividing the velocity by '2'. This will help reveal any shortcomings in rotation once we start moving the cursor diagonally.

Do you have any bright insights or suggestions to offer?

const scaleX = 1 + velocityX / 2;
const scaleY = 1 + velocityY / 2;

Answer №1

To achieve this special effect, follow these steps starting from the end:

  1. Utilize CSS transforms like scaleX() and scaleY()
  2. Determine the cursor movement velocity in both x and y axes
  3. 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fixing the issue of a div exceeding the height of its parent div in Tailwindcss

One issue I'm encountering is with my card element, which has a fixed height of h-80 in Tailwind. Typically, I use this card within a grid. However, I recently added a div inside the card that is larger than its parent div, and I want it to scroll ve ...

AngularJS framework may encounter an issue where changes in $scope data do not reflect in the view

I have noticed that when I reload the data using my function, the view does not change. After some research, I found that adding $scope.$apply() should solve this issue. However, I am encountering an error when trying to implement this solution. https://d ...

Implementing Voting Functionality with Ajax Submission

Can anyone help me with getting ajax functionality to work properly for my Acts_As_Votable buttons? Here's the current code I have: post_controller.rb def favorite @post = Post.find(params[:id]) @post.upvote_from current_user respond_to do |f ...

Increasing the nth-child Selector in Jquery

Referring to this I am looking to cycle through the nth-child selector, which involves: var i = 1; var tmp = $(this).find('td:nth-child(i+1)'); // I wonder how this can be achieved i++; I have rows with dynamically generated columns i ...

What is the best way to cancel a request within an HTTP-interceptor?

Within an application, I have established the following URL structure for the API: // public public/url-xyz // private dashboard/url-xyz To avoid unnecessary requests, what is the most effective method for canceling a request? My current approach involv ...

The 'in' operand is invalid

I am encountering a JavaScript error: "[object Object]" TypeError: invalid 'in' operand a whenever I attempt to perform an AJAX request using the following code: .data("ui-autocomplete")._renderItem = function( ul, item ) { return $( " ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

Error encountered when simulating the effect of calling 'insertPlayerData' function: ReferenceError - currentUserId has not been defined

PlayerList = new Mongo.Collection('players'); UerAccounts = new Mongo.Collection('user'); if(Meteor.isClient){ Template.leaderboard.helpers({ 'player':function(){ var currentUserId = Meteor.userId(); return Play ...

Having trouble connecting to the http json service in AngularJS

I recently started learning angularjs and I'm facing an issue with my code. There seems to be a flaw in the code and I'm uncertain about it. From a java perspective, the httpController has a nested function defined inside. Below is the code sn ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...

Include a query parameter each time a page is added to bookmarks

Is there a way to automatically add a query parameter to a page URL when bookmarked using Chrome? For example, if I bookmark https://www.example.com, can it be saved as https://www.example.com/?bookmarked? I'm thinking I might need to use JavaScript ...

Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML. function sendData() { var formData = new FormData( document.querySelector("form") ); var xmlHttp = new XMLHttpRequest(); xmlHttp.open("post", "test.php",true); ...

Tips for utilizing template tags with the Vue root component

As I work on improving a page within a web application with Vue, I have typically written single file components and have preferred defining the html template at the start of the file using the <template> tag. Is there a method to utilize this tag w ...

Having trouble with collision detection in Three.js?

I am currently working on creating a 3D Breakout game using three.js. Most of the collision detection for the walls is already implemented, but I'm facing difficulties with the collision against the paddle. Below is my code snippet: // A 3D breakout ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...

The firebase collection's model doesn't include an add function within its nested collection

I'm currently developing an application where I aim to utilize Firebase for real-time data storage within the context of the Backbone framework. The issue I am facing is as follows: I have a sub-level model and collection, both of which are standar ...

Nested within an it block are Protractor Jasmine describe blocks

Initially, the code provided below appears to be functioning properly. However, I have not come across anyone using this method before, leading me to question its validity and potential unforeseen drawbacks. The scenario involves writing an end-to-end tes ...

What is the process behind managing today's Google image of the day?

After coming across the javascript picture control on the Google search page, I became interested in replicating it myself. The feature zooms in on a picture when hovering over it, but I couldn't locate the HTML code they were using for it. Is there ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

What steps can be taken to obtain the fully computed HTML rather than the source HTML?

Is there a way to access the final computed HTML of a webpage that heavily relies on javascript to generate its content, rather than just the source HTML? For example, if a page contains script functions that dynamically generate HTML, viewing the page sou ...