Is it possible to create a mouse-following effect with lighting using Javascript

Recently, I've been honing my Javascript skills and decided to create a follow-mouse function. After successfully implementing it, I started brainstorming a new concept that I'm unsure is achievable.

Is there a way to develop an "orb of vision" that tracks the mouse's movement, illuminating everything within its radius? Imagine using a torch to illuminate a specific area where your cursor hovers.

https://i.stack.imgur.com/qpzXk.png

  • NOTE: I'm not seeking someone to write the code for me. Instead, I'm looking for insights to guide my learning process. I'm eager to tackle this project on my own but could use some pointers!
function trackMouseMovement(e) {
    var x = document.getElementById('x_show');
    var y = document.getElementById('y_show');

    x.innerHTML = e.clientX;
    y.innerHTML = e.clientY;

    document.getElementById("followDiv").style.left = event.clientX - 15 + "px";
    document.getElementById("followDiv").style.top = event.clientY - 15 + "px";
}

document.onmousemove = trackMouseMovement;
#followDiv {
    background-color: lightblue;
    height: 30px;
    width: 30px;
    position: absolute;
}
<p id="x_show">0</p>
<p id="y_show">0</p>
<div id="followDiv"></div>

Answer №1

One alternative method without using canvas is:

  • Change the page background color to black
  • Apply 'border-radius: 50%;' to round the borders of #followDiv
  • Set an image as the background of this div
  • Adjust the background position to move in the opposite direction of the mouse

Edit:

  • Add a finishing touch by softening the edges with box-shadow

function trackMouse(e) {
  var x = document.getElementById('x_show');
  var y = document.getElementById('y_show');

  x.innerHTML = e.clientX;
  y.innerHTML = e.clientY;

  var followDiv = document.getElementById("followDiv");
  followDiv.style.left = event.clientX - 60 + "px";
  followDiv.style.top = event.clientY - 60 + "px";
  followDiv.style.backgroundPositionX = (-event.clientX) + 'px';
  followDiv.style.backgroundPositionY = (-event.clientY) + 'px';
}

document.onmousemove = trackMouse;
body {
  background: black;
}

#followDiv {
  background-color: lightblue;
  height: 120px;
  width: 120px;
  position: absolute;
  border-radius: 50%;
  box-shadow: 0 0 12px 12px black inset, 
               /* workaround for a soft edge issue */ 
               0 0 2px 2px black inset, 0 0 2px 2px black inset, 0 0 2px 2px black inset;
  background: url(https://dl.dropboxusercontent.com/u/139992952/multple/annotateMe.jpg) no-repeat;
}
<p id="x_show">0</p>
<p id="y_show">0</p>
<div id="followDiv"></div>

Answer №2

Hey @Bulent Vural, I came up with a solution for this issue. It seems like resizing the circle to fit the screen is causing it to appear larger than intended.

One workaround I found was to add additional instances of "black" within the code, but this resulted in a less visually appealing outcome.

    function trackMouseMovement(e)
    {
        var x = document.getElementById('x_show');
        var y = document.getElementById('y_show');

        x.innerHTML = e.clientX;
        y.innerHTML = e.clientY;

        document.getElementById("followDiv").style.left = event.clientX-2000+"px";
        document.getElementById("followDiv").style.top = event.clientY-2000+"px";

    }
    document.onmousemove = trackMouseMovement;
</script>
 html, body {margin: 0; height: 100%; overflow: hidden}
        #followDiv {
            /* background-color: lightblue; */
            height: 4000px;
            width: 4000px;
            position: absolute;

            background: -webkit-radial-gradient(circle, rgba(248, 255, 252, 0),black);
            background: -o-radial-gradient(circle, rgba(248, 255, 252, 0),black);
            background: -moz-radial-gradient(circle, rgba(248, 255, 252, 0),black);
            background: radial-gradient(circle, rgba(248, 255, 252, 0),black);
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <title></title>
  
</head>
<body>
  <p id="x_show">0</p>
  <p id="y_show">0</p>
  <div id="followDiv"></div>
</body>

Answer №3

Here is a solution that may assist you in achieving your desired outcome.

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

$("#canvas").mousemove(function(e){handleMouseMove(e);});

var radius=30;

var img=new Image();
img.onload=function(){
  draw(150,150,30);
}
img.src='https://dl.dropboxusercontent.com/u/139992952/multple/annotateMe.jpg'


function draw(cx,cy,radius){
  ctx.save();
  ctx.clearRect(0,0,cw,ch);
  var radialGradient = ctx.createRadialGradient(cx, cy, 1, cx, cy, radius);
  radialGradient.addColorStop(0, 'rgba(0,0,0,1)');
  radialGradient.addColorStop(.65, 'rgba(0,0,0,1)');
  radialGradient.addColorStop(1, 'rgba(0,0,0,0)');
  ctx.beginPath();
  ctx.arc(cx,cy,radius,0,Math.PI*2);
  ctx.fillStyle=radialGradient;
  ctx.fill();
  ctx.globalCompositeOperation='source-atop';
  ctx.drawImage(img,0,0);
  ctx.globalCompositeOperation='destination-over';
  ctx.fillStyle='black';
  ctx.fillRect(0,0,cw,ch);
  ctx.restore();
}


function handleMouseMove(e){

  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  draw(mouseX,mouseY,30);

}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Move mouse to reveal image with "flashlight"</h4>
<canvas id="canvas" width=300 height=300></canvas>

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

Firefox throwing XML parsing error when SVG is encoded as data URI

Check out my codepen demo showcasing the issue: codepen.io/acusti/pen/mJmVRy Encountering an error when trying to load svg content in Firefox: XML Parsing Error: unclosed token Location: data:image/svg+xml;utf8,<svg%20viewBox='0%200%20120%2 ...

Choose from a range of knockout fetching options for the select feature and choose one

Upon loading my page, there is a <select> element positioned. I am utilizing knockout data-bind to retrieve the values like this: <select data-bind="attr: { id: 'input-' + id(), required: !allowBlank }, option ...

updateStatusCallback function is not defined in the Facebook example using jQuery

I've been trying to incorporate Facebook integration into my HTML code, specifically adding features like Facebook login and sharing functionalities. However, I've hit a roadblock in the process. Even after searching extensively for solutions, I ...

aligning adaptable grid on the screen

Is anybody able to assist me in vertically centering the responsive matrix below so that it is equidistant from the left and right edges of the screen (parent element has a width of 100%)? Any help would be greatly appreciated. Here is my code: <!DOC ...

What is the best way to pass a parameter with a slash in a GET request using jQuery's .ajax() function?

I'm currently faced with the task of generating a specific URL to make an API call using jQuery's .ajax() function: https://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&zipCode=02144&date=2016-11-26&distance=25& ...

Tips for updating the color scheme in your CSS file by making hue adjustments to all colors

I have a CSS file and I am looking to automatically generate multiple color variations of the file by altering the hue, similar to using the "colorize" function in GIMP. I came across a tool that does exactly what I need at , however it does not support t ...

Submitting a JSPX form to interact with PHP backend

Can a JSP/JSPX form be used to submit data to a PHP file? The PHP file will handle validation and database updates, then send a response back to the same JSP/JSPX form. The process should be done using AJAX with jQuery. What steps are involved in achievi ...

Creating a table from a PHP associative array

I've been attempting to organize an associative array in ascending order and then display it in an HTML table, but I've hit a roadblock with an error. I tried searching for solutions here on SO and followed the advice provided in some threads: P ...

Blending ThreeJS graphics with typical HTML/CSS pages

Is it feasible to swap out an animated image in the background of a website with JSON geometry while keeping the HTML elements in the forefront? I've attempted to utilize DOM Elements in ThreeJS without success. I experimented with incorporating my JS ...

Guide on transferring PHP database information to JQuery and then adding it to a Table

Looking to utilize user input to filter and display database data in an HTML table? That's exactly what I'm trying to achieve. My goal is to use the user's input as a filter for querying the database, then present the results neatly in a tab ...

Safari browser not supporting CSS @property --rotate functionality

This card's animation is functioning well in Chrome, but it is not compatible with Safari and Mozilla Firefox. I suspect the issue lies with the @property --rotate, as it is no longer supported by Safari. Therefore, I am searching for an alternative ...

What is the proper way to reference a property's value within another property of the same JavaScript Object?

Within a Gulp.js file (or any Javascript file), I have defined paths in a Javascript object: var paths = { devDir : 'builds/development/', devDirGlobs : this.devDir+'*.html' } I am attempting to reference the pro ...

Incorrect display of French characters in emails

Issues arise when sending emails with French characters, as they are not displaying correctly in the mail body. I made sure to include the following code in my HTML page: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> Despit ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

You need a function property for the child component to be updated

I recently encountered an unusual issue with my React components that has left me puzzled. Here is a condensed version of the app: class Child extends React.Component { componentDidUpdate(prev) { if (!prev.isActive && this.props.isActive) ...

Border becomes dashed when dragging and dropping

I am working on enabling drag and drop functionality for users. When an item is lifted from its original position, a gray dashed box should appear in its place. As the item is moved closer to another spot, the containers adjust to create a target area (gra ...

Searching for values in an array using the $elemMatch operator in MongoDB 2.6 without the need for the $eq operator

Looking to retrieve all users with a specified objectId in an array. Here is the query I'm using: var query = { 'arrayOfIds': { $elemMatch: { $eq: id } }, }; This query functions well in mongodb 3.0. However, in mongodb 2.6, there isn& ...

Can you guide me on how to establish a cookie within a selenium webdriver javascript script?

I am trying to figure out how to set a cookie using a basic webdriver script: WDS.sampleResult.sampleStart(); //WDS.driver.manage().addCookie(new Cookie("connect.sid", "s%3AeexeZcd_-S23Uh30e3Dmd4X9PskWF08s6m5hDurDa5Jj66SupmmiqvKEjAg6HGigl0o0V%2B9R7m4", ...

unable to obtain desired font in the final result

I have encountered an issue where the certificate theme I am storing in the database as HTML appears fine in the browser output, but when fetched and displayed in a PDF format, the normal font output is shown instead. I am unsure of what I might be doing w ...

Steps for refreshing Google reCAPTCHA on an AJAX-enabled webpage

I am encountering an issue with two captchas on my website. One captcha is loaded upon refresh, while the second captcha is loaded on a different page via ajax. The problem arises when I click on the "No" button after selecting it on the second page. I wan ...