How to increase the size of an element as the mouse approaches?

I just messed around in jsfiddle trying to resize the cell base at the mouse position. Increasing the size of the box when moving the mouse is simple, just get the distance. However, I want to do the opposite; I want the drawer to grow in size as the mouse zooms in and out as the mouse moves away. I could not come up with any formulas for this. I feel that there might 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 the link to the fiddle: http://jsfiddle.net/gSDPq/

Any help is appreciated, thanks

+6
source share
3 answers

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

This should disappear if the mouse is 200 pixels or more, and gradually increase to 200 pixels as you approach the middle. Adjust the numbers as needed (for example, divide the Math.sqrt() by 2 to reduce the effect of this distance, or adjust 200 to affect the maximum size)

+7
source

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); 
+1
source

I'm not sure that Kolink's answer really did what you wanted to do. It seems you want the drawer to expand as the mouse approaches it.

Just subtracting both x and boxX from some predefined box size value, you need to do this:

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

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

+1
source

Source: https://habr.com/ru/post/943665/


All Articles