Adjust the size of the mouse cursor in real time

I'm currently in the process of developing a project where I want to create a web application with a mouse cursor that appears as a circle with a customizable radius, which can be altered by the user. The main requirement is for this custom cursor to only be visible within a specific element on the webpage, while still allowing user interaction through clicks.

As far as my brainstorming goes, it seems like my potential options involve using JavaScript to change the cursor image, but this would mean needing an image for every possible value of r selected by the user.

Alternatively, I could consider implementing a canvas element that tracks the cursor and draws a circle with the specified radius within it. However, there is uncertainty regarding whether the original element will retain its ability to receive user clicks with this approach.

Do you have any ideas or suggestions? Is there a more efficient solution that I might not be considering?

Answer №1

Using canvas makes it easy to achieve this.

All you need to do is place the clickable element above the canvas.

Track the mouse position on the top layer (the clickable element) and utilize these coordinates to draw on the canvas underneath.

Check out this code snippet I prepared for you:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>test</title>
<style type="text/css">
#hold { margin:0 auto; width:500px; height:500px; border:1px solid #000; }
#canvas { float:left; }
#top-layer { position:absolute; z-index:1; width:500px; height:500px; cursor:crosshair; }
</style>
</head>
<body>

<div id="hold">

  <canvas id="canvas" width="500" height="500"></canvas>

  <div id="top-layer" onmousemove="trackMouse(event);">
    <ul>
      <li><a href="http://www.google.com">Test Link (redirects to Google)</a></li>
      <li><a href="http://www.google.com">Test Link (redirects to Google)</a></li>
      <li><a href="http://www.google.com">Test Link (redirects to Google)</a></li>
      <li><a href="http://www.google.com">Test Link (redirects to Google)</a></li>
      <li><a href="http://www.google.com">Test Link (redirects to Google)</a></li>
      <li><a href="http://www.google.com">Test Link (redirects to Google)</a></li>
    </ul>
  </div>

</div>

<script type="text/javascript">

var ctx = document.getElementById('canvas').getContext('2d');

function trackMouse(event) {
  ctx.globalCompositeOperation = "source-over";
  ctx.clearRect(0, 0, 500, 500);

  this.r = 25; // Radius of circle
  this.x;
  this.y;

  this.x = event.clientX - document.getElementById('canvas').offsetLeft;
  this.y = event.clientY - document.getElementById('canvas').offsetTop;

  ctx.strokeStyle = '#000';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.stroke();
};

</script>
</body>
</html>

Answer №2

Feel free to utilize a canvas for this task. As previously mentioned, using various mouse cursor images can be quite cumbersome.

With every Javascript event that occurs, it impacts all elements on the page. This means that if there is a link within a div and it gets clicked, both the link and div will register the click event. (Although I cannot recall the exact order at the moment)

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

Utilizing Angular's Local Storage Module to efficiently store and manage various elements within an array in Local Storage

I'm facing an issue with storing and retrieving an array from localStorage using the Angular Local Storage Module. Despite following the necessary steps, I am only able to retrieve the last element added to the array. Can anyone provide insights on wh ...

Adding various image files to the canvas

I am facing an issue with my code where I need to find images inserted by the user into a div and then combine them into one image in a canvas when the "snap" button is clicked. While I can successfully locate, position, and resize the images inside the ca ...

Guard your website against Backdoor/PHP.C99Shell, also known as Trojan.Script.224490

Recently, my website fell victim to a trojan script infiltration. Someone maliciously inserted a file named "x76x09.php" or "config.php" into the root directory of my webspace. This file, with a size of 44287 bytes and an MD5 checksum of 8dd76fc074b717fcc ...

"An error occurred while trying to access the data for a new user on the snapshot object while navigating to the screen. It seems that the object is

When I navigate to the screen, I use componentDidMount to trigger fetchNewUser which is meant to detect a new user and update it if necessary. However, I encounter an issue where on initial navigation to the screen, it returns undefined is not an object ...

How can JavaScript be used to create a unique signup and login process on

I am struggling with storing sign up and login details in JavaScript. In my previous project, I used PHP and a database to handle this information, so transitioning to JavaScript has been challenging. Here is an example of the sign-up HTML code: <!DOC ...

Calculating the total of an array's values using JavaScript

Receiving information from an API and looking to aggregate the values it contains. Consider the following code snippet: function totalPesos(){ $http.get('/api/valueForTest') .then(function(data){ $scope.resumePesos = data.data.Re ...

Designing a table with specific limitations on the width of each column

Having an issue with an HTML table that has 3 columns and specific restrictions: Column 1: fixed width, no text wrapping (small text) Column 2: allows text wrapping Column 3: contains descriptive long text with wrapping enabled A row should span the enti ...

Improprove the performance of external banner ads by utilizing asynchronous loading or caching techniques

My website is slick, elegant, and loads quickly - that is until the banner ads come into play! A delay of up to 10 seconds in loading occurs due to waiting for the ads, which is frustrating considering the effort I put into optimizing the rest of the site. ...

How can I keep the cursor in place while editing a phone number field on Sencha ExtJS?

After one backspace move, the cursor on the phone number field automatically moves to the end which can be inconvenient if the user only wants to edit the area code. Unfortunately, I am unable to post images at the moment due to insufficient reputation. B ...

Ways to align items in the middle of a list

I'm having trouble figuring this out. How can I properly center list items within the ul? body {margin: 0} ul { width: 1000px; margin: 0 auto; padding: 0; list-style-type: none; margin-top: 30px; overflow: hidden; background-color: # ...

The function does not provide an output of an Object

I have two JavaScript classes, Controller.js and Events.js. I am calling a XML Parser from Events.js in Controller.js. The Parser is functioning but not returning anything: SceneEvent.prototype.handleKeyDown = function (keyCode) { switch (keyCode) { ...

Using jQuery to trigger alert only once variable has been updated

I have a question that may seem too basic, but I can't find the solution. How do I make sure that the variables are updated before triggering the alert? I've heard about using callbacks, but in this case, there are two functions and I'm not ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Attempting to alert a particular device using Flutter for notification delivery

Currently, I am developing a Chat app using Flutter and attempting to send notifications to specific devices through Firebase functions. Initially, I retrieve the device token and store it in Firebase. Now, my challenge lies in fetching the token and invok ...

What is the method for including a TabIndex property in a JSON file?

https://i.sstatic.net/ISi72.png I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

Encountering a jQuery error while attempting to initiate an AJAX request

I'm currently working on a project in SharePoint and I want to integrate JQuery to make an ajax call from the homepage. However, when I attempt to make the call, I encounter an error stating "Array.prototype.slice: 'this' is not a JavaScript ...

send JSON data to a Spring MVC endpoint

Here is the controller signature I have tried using @RequestBody: @RequestMapping(value = "/Lame", method = RequestMethod.POST) public @ResponseBody boolean getLame(@RequestParam String strToMatchA, @RequestParam String strToMatchB) {} This is the json I ...

What is the process for transferring a JSON data object to the server with JavaScript XMLHttpRequest?

When I attempt to send an XMLHttpRequest to a PHP server, I am encountering difficulties in getting the $_POST or $_REQUEST object to be filled with the data I am sending using JavaScript: var r = new XMLHttpRequest; r.open("POST", "http://url.com", true ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: https://i.sstatic.net/GpvfC.png <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={th ...

In HTML, an important concept to understand is how float:left is necessary when the combined widths of child blocks equal

Apologies if my question seems redundant, I was having trouble finding the right search terms. Let's discuss a scenario with a parent <div> containing two inline-block children, each with a width of 50%. If we don't apply overflow: hidden ...