Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase element size as mouse gets closer?

I was just messing around in jsfiddle trying to resize a box base on the mouse position. Making the box larger as the mouse moves away is simple, just get the distance. However, I want to do the opposite; I want the box to increase in size as the mouse gets closer and decrease as the mouse moves away. I haven't been able to think up any formulas for this. I feel there could be something really simple that I am missing.

<div id="box"></div>

#box { height: 100px; width: 100px; background: black; }

var box = document.getElementById('box');

// center point of the box
var boxX = 50;
var boxY = 50;

document.addEventListener('mousemove', function(e) {
    var x = e.pageX,
        y = e.pageY;

    var dx = x - boxX,
        dy = y - boxY;

    var distance = Math.sqrt(dx *dx + dy * dy);

    box.style.width = box.style.height = distance + 'px';

}, false);

Here is a link to the fiddle: http://jsfiddle.net/gSDPq/

Any help is appreciated, Thanks

like image 246
dotfury Avatar asked Apr 25 '13 22:04

dotfury


3 Answers

Try distance = Math.max(0,200-Math.sqrt(dx*dx + dy*dy));

This should have the box disappear when the mouse is 200px or more away, and steadily grow to 200px in size as you get nearer the middle. Adjust numbers as needed (for instance, divide the Math.sqrt() part by 2 to reduce the effect that distance has, or adjust the 200 to affect the max size)

like image 143
Niet the Dark Absol Avatar answered Nov 14 '22 03:11

Niet the Dark Absol


jsfiddle

var box = document.getElementById('box');  
// center point of the box
var boxX = 50;
var boxY = 50;
var ux=500, uy=500;// 1.stage
document.addEventListener('mousemove', function(e) {
    var x = e.pageX,
        y = e.pageY;

    var dx = ux-(x - boxX),
        dy = uy-(y - boxY);// 2.stage

    var distance = Math.sqrt(dx *dx + dy * dy);

    box.style.width = box.style.height = distance + 'px';

}, false);
like image 21
aliveli Avatar answered Nov 14 '22 05:11

aliveli


I'm not sure that Kolink's answer actually did what you wanted to do. You seem to want the box to grow when the mouse is getting closer to it.

Just subtracting both x and boxX from some predefined box size value should do that:

var dx = 400 - x - boxX,
    dy = 400 - y - boxY;
if(dx<0) dx = 0;
if(dy<0) dy = 0;

http://jsfiddle.net/gSDPq/3/

like image 31
Oleg Mikheev Avatar answered Nov 14 '22 05:11

Oleg Mikheev