How to increase element size as mouse gets closer? - javascript

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

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)

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);

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/

Related

How to position the center of a div to the center of the mouse cursor on mouse movement with JS?

I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements.
Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor.
WORKFLOW
The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. When the mouse leaves the div it should be hidden.
CODE
HTML post item:
<article class="col-md-4 col-sm-6 post-entry">
<a href="#" title="">
<figure class="post-thumb">
<img src="http://placehold.it/300x300" alt="">
<div class="pointer" style="background: red;"></div>
</figure><!-- End figure.post-thumb -->
</a>
</article><!-- End article.col-md-4 post-entry -->
JS:
$('.entry .post-entry').each(function() {
$(this).on("mouseenter", mouseEnter);
$(this).on("mousemove", mouseMove);
$(this).on("mouseleave", mouseLeave);
});
function mouseEnter(event) {
console.log('enter');
var target = $(this);
var dot = target.find('.pointer');
var mX = (event.clientX);
var mY = (event.clientY);
set(
dot, {
x: mX,
y: mY,
force3D: !0
}
);
};
function mouseMove(event) {
console.log('move');
var target = $(this);
var dot = target.find('.pointer');
// var offset = target.offset();
// var width = target.width();
// var height = target.height();
// var top = offset.top;
// var left = offset.left;
var mX = (event.clientX);
var mY = (event.clientY);
$(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');
};
function mouseLeave(event) {
console.log('leave');
var target = $(this);
var dot = target.find('.pointer');
$(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');
};
function onClick(event) {
event.preventDefault();
console.log('click');
};
function set(el, obj) {
var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
return dot;
};
PROBLEM / DEMO
As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. It will be offset the mouse. See live demo here
I tried already something like this for the mX and mY variables, but with no succes:
var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();
Also the answer from #hiEven doesn't work and will let me with the same issue:
transform: calc(mX - 50%, mY - 50%)
I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me.
UPDATE
I created two new Codepen projects:
Use without images: http://codepen.io/anon/pen/GqGOLv. When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item.
When I use images: http://codepen.io/anon/pen/QExOkx. The problem by this example is that when you at the very top of the first column, you will see the brown pointer. When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images.
Both pointer should follow the mouse cursor correctly. And I am searching for a solution that works with the use of an image.
Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero.
So I don't know what's missing and why it only works with the first example (without images) and only for the first item?
Try the code below
<html>
<head>
<style>
#mouse_div{
position: absolute;
background-color: black;
}
</style>
<script>
var div_width = 100;
var div_height = 100;
var div_x, div_y;
function mouse_position(event){
var mouse_x = event.clientX;
var mouse_y = event.clientY;
document.getElementById("mouse_div").style.width = div_width + "px";
document.getElementById("mouse_div").style.height = div_height + "px";
div_x = mouse_x - (div_width / 2);
div_y = mouse_y - (div_height / 2);
document.getElementById("mouse_div").style.left = div_x + "px";
document.getElementById("mouse_div").style.top = div_y + "px";
}
</script>
</head>
<body onmousemove="mouse_position(event)" onload="mouse_position(event)">
<div id="mouse_div"></div>
</body>
</html>
This program gets the position of your mouse, the width, and the height of the div. Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). The program then does the same thing for the mouse y. Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be.
Note: you must make sure that the position of the div is set to absolute or the program will not work.
I assume you want the circle being center of your mouse, right?
try do this
transform: `translate(calc(${mx}px - 50%), calc(${my}px - 50%))
here is the demo
Based on my latest update, I did not conform to the correct formula that is needed to center the element .pointer to the mouse.
In order to use the following calculation within mouseMove:
var mX = (event.clientX);
var mY = (event.clientY);
Should be changed to this:
var height = dot.height();
var width = dot.width();
var offset = target.offset();
var w = target.width();
var h = target.height();
var top = offset.top;
var left = offset.left;
var mX = (event.clientX - left) - width / 2 - 15; // 15 = padding
var mY = (event.clientY - top) - height / 2;
So this formule is considering that the following DOM element .pointer will follow the mouse movements of the user. I don't know exactly why this working, but the offset from the previous item will be decreased from the current clientX coordinates, so the position of the second item is reset to zero, so the pointer will start at the left side of each item.
Here is a working demo of above code: http://codepen.io/anon/pen/AXdxZO?editors=0110

RaphaelJS : Stop drag when image out of frame

i have a RaphaelJS paper which has a set that contains an image and other elements. The Image is larger than the paper, and the user can drag it around.
However i want the drag to stop so that the image border is never visible, meaning that the user will not the the white margins. I have tried several ways but i keep getting weird results and i cant wrap my head around it.
I can get the top left corner of the image and the remaining corners of the image with calculation. Thank you for your time.
UPDATE : i have added a JSFiddle example
In the example i have added a condition that's supposed to keep the top left cornet outside the canvas, but as you can see there are a lot of glitches and bugs with this.
here is an image illustrating the desired result
Code :
Raphael.st.draggable = function(index) {
var me = this,
lx = 0,
ly = 0,
ox = 0,
oy = 0,
moveFnc = function(dx, dy) {
x = set.getBBox().x;
y = set.getBBox().y;
console.log(x+":"+y);
lx = dx + ox;
ly = dy + oy;
if(x+dx < 0 && y+dy < 0)//REMOVE THIS CONDITION FOR FREE DRAG
me.transform(',,320,240,'+'t' + lx + ',' + ly);
},
startFnc = function() {},
endFnc = function() {
ox = lx;
oy = ly;
};
this.drag(moveFnc, startFnc, endFnc);
};
width = 640;
height = 480;
paper = Raphael(cur_id, width, height),
image = paper.image('http://edwardtufte.com.s3.amazonaws.com/Thinking%20Eye/ParisMap.gif', 0, 0,950,805)
set = paper.set();
set.push(image);
paper.canvas.style.backgroundColor = "#FF0000"
set.draggable();
If I understand what you're looking for correctly, it looks like you're only missing the limiting part in your moveFnc drag event.
Something like this in place of your lx and ly assignments should limit the image to be scrollable only to the edges:
if (dx + ox <= 0){
if (dx + ox > width - image.attrs.width){
lx = dx + ox;
}
else{
lx = width - image.attrs.width;
}
}
if (dy + oy <= 0){
if (dy + oy > height - image.attrs.height){
ly = dy + oy;
}
else{
ly = height - image.attrs.height;
}
}
Positive translation will allow the image to drag to the left and down. If we limit the translation to negative values, it will stop at the left and top edges. For the right and bottom edges, we limit the negative translation to values bigger than the width of the paper minus the width of the image.

Distance measurement logic

Boy it was hard to give this problem a name...
I've been working on this "progress bar" logic, that when ever the user moves
his/her mouse - the indicator (in this case its progress bar) shows how close cursor is to the wanted object.
Basically it's like "hot 'n cold" kind of thing.
Here's the fiddle
...and this is the problem part
relativeDistance = ((maxMouseDistance - distance) / maxDistance);
if ((maxMouseDistance - distance) > maxDistance){
relativeDistance = 1- (((maxMouseDistance) / maxDistance) -1);
}
Since my code and distance measurements are based on trigonometry, it has a small problem: There's actually atleast two points on the screen, where the wanted distances are equal.
Try it and you'll notice what I mean.
Any ideas on how I could get rid of that...It's propably because of the logics, but I just don't see it.
Does this jsFiddle do what you want?
It uses the nearest corner to the mouse rather than the farthest corner. It will show 0% when the mouse is in any corner, and a positive percentage as the mouse approaches the target, even if the target is off-centre.
(function () {
var mX
, mY
, distance
, $distance = $('#distance')
, $element = $('#thetarget')
, maxMouseDistance
, relativeDistance;
var theWidth = $(document).width();
var theHeight = $(document).height();
$("#theWidth").text(theWidth);
$("#theHeight").text(theHeight);
function pythagoras(length, height) {
var length2 = length * length
, height2 = height * height
return Math.sqrt((length2 + height2));
}
/**/
var target = $("#thetarget");
target.css({
cursor: "default"
, border: "1px solid black"
, margin: 0});
var position = target.position(); // top left of target element
var tX = Math.floor(position.left)
var tY = Math.floor(position.top)
$("#targetPosition").text(tX + ":" + tY);
var corners = [
[0, 0]
, [theWidth, 0]
, [theWidth, theHeight]
, [0, theHeight]
]
function distanceToNearestCorner(x, y) {
var cornerX = x < tX ? 0 : theWidth
var cornerY = y < tY ? 0 : theHeight
return pythagoras(cornerX - tX, cornerY - tY)
}
/*Mouse movement tracking*/
$(document).mousemove(function (e) {
/*Get mouse coordinates*/
mX = e.pageX;
mY = e.pageY;
/*calculate distance between mouse and element*/
distance = pythagoras(tX - mX, tY - mY);
maxMouseDistance = distanceToNearestCorner(mX, mY)
relativeDistance = ((maxMouseDistance - distance) / maxMouseDistance);
$distance.text(distance);
var decimals = distance / 100;
var percents = 100 - (distance / 100);
$("#mouse").text(mX + ":" + mY);
//$("#distanceDecimals").text(decimals);
//$("#dFarCorner").text(maxDistance);
$("#md2FarCorner").text(maxMouseDistance);
$("#formula").text("(E to C max / M to C max) / (M to E distance/100)");
$("#theNumber").text(relativeDistance);
$('.fill').width((relativeDistance * 100) + "%");
});
})();
It doesn't update all the fields, but it does update the progress bar.
Original answer
You seem to have plenty of functions in there which are not being called.
Here's one that I have rewritten... but it doesn't get called:
function calculateDistance(elem, mouseX, mouseY) {
var deltaX = elem.offset().left - mouseX;
var deltaY = elem.offset().top - mouseY;
var delta2 = deltaX * deltaX + deltaY * deltaY;
var delta = Math.floor(Math.sqrt(delta2))
return delta
}
var elem = document.getElementById("targetPosition")
var relativeDistance = calculateDistance(elem , mX, mY)
In my implementation, elem is the HTML element that you consider to be the target. My function is an application of Pythagoras' theorem: it returns the square root of the sum of the distance from the target along the x and y axes, giving the length of the shortest line between the mouse and the target.
When I insert this into your jsFiddle, I see 0 appearing in the M2E Distance field when my cursor is just above the "T" of "Target".
Is this what you are looking for?
Your logic is correct. It's called a locus. http://www.bbc.co.uk/schools/gcsebitesize/maths/geometry/locirev1.shtml

Getting the certain positions within a canvas

I am using Kinetic.js for this, but I figure this is not Kinetic specific. The problem is as follows:
I am loading an image in a canvas, and I then use Kinetic to rotate this image. How do I get the x and y of, for example, leftmost point of this image?
Try doing the calculations manually:
var theta = image.getRotation*Math.PI/180.;
// Find the middle rotating point
var midX = image.getX() + image.getWidth()/2;
var midY = image.getY() + image.getHeight()/2;
// Find all the corners relative to the center
var cornersX = [image.getX()-midX, image.getX()-midX, image.getX()+image.getWidth()-midX, image.getX()+image.getWidth()-midX];
var cornersY = [image.getY()-midY, image.getY()+image.getHeight()-midY, midY-image.getY(), image.getY()+image.getHeight()-midY];
// Find new the minimum corner X and Y by taking the minimum of the bounding box
var newX = 1e10;
var newY = 1e10;
for (var i=0; i<4; i=i+1) {
newX = min(newX, cornersX[i]*Math.cos(theta) - cornersY[i]*Math.sin(theta) + midX);
newY = min(newY, cornersX[i]*Math.sin(theta) + cornersY[i]*Math.cos(theta) + midY);
}
// new width and height
newWidth = midX - newX;
newHeight = midY - newY;

Pinch to zoom with CSS3

I'm trying to implement pinch-to-zoom gestures exactly as in Google Maps. I watched a talk by Stephen Woods - "Creating Responsive HTML5 Touch Interfaces” - about the issue and used the technique mentioned. The idea is to set the transform origin of the target element at (0, 0) and scale at the point of the transform. Then translate the image to keep it centered at the point of transform.
In my test code scaling works fine. The image zooms in and out fine between subsequent translations. The problem is I am not calculating the translation values properly. I am using jQuery and Hammer.js for touch events. How can I adjust my calculation in the transform callback so that the image stays centered at the point of transform?
The CoffeeScript (#test-resize is a div with a background image)
image = $('#test-resize')
hammer = image.hammer ->
prevent_default: true
scale_treshold: 0
width = image.width()
height = image.height()
toX = 0
toY = 0
translateX = 0
translateY = 0
prevScale = 1
scale = 1
hammer.bind 'transformstart', (event) ->
toX = (event.touches[0].x + event.touches[0].x) / 2
toY = (event.touches[1].y + event.touches[1].y) / 2
hammer.bind 'transform', (event) ->
scale = prevScale * event.scale
shiftX = toX * ((image.width() * scale) - width) / (image.width() * scale)
shiftY = toY * ((image.height() * scale) - height) / (image.height() * scale)
width = image.width() * scale
height = image.height() * scale
translateX -= shiftX
translateY -= shiftY
css = 'translateX(' + #translateX + 'px) translateY(' + #translateY + 'px) scale(' + scale + ')'
image.css '-webkit-transform', css
image.css '-webkit-transform-origin', '0 0'
hammer.bind 'transformend', () ->
prevScale = scale
I managed to get it working.
jsFiddle demo
In the jsFiddle demo, clicking on the image represents a pinch gesture centred at the click point. Subsequent clicks increase the scale factor by a constant amount. To make this useful, you would want to make the scale and translate computations much more often on a transform event (hammer.js provides one).
The key to getting it to work was to correctly compute the point of scale coordinates relative to the image. I used event.clientX/Y to get the screen coordinates. The following lines convert from screen to image coordinates:
x -= offset.left + newX
y -= offset.top + newY
Then we compute a new size for the image and find the distances to translate by. The translation equation is taken from Stephen Woods' talk.
newWidth = image.width() * scale
newHeight = image.height() * scale
newX += -x * (newWidth - image.width) / newWidth
newY += -y * (newHeight - image.height) / newHeight
Finally, we scale and translate
image.css '-webkit-transform', "scale3d(#{scale}, #{scale}, 1)"
wrap.css '-webkit-transform', "translate3d(#{newX}px, #{newY}px, 0)"
We do all our translations on a wrapper element to ensure that the translate-origin stays at the top left of our image.
I successfully used that snippet to resize images on phonegap, using hammer and jquery.
If it interests someone, i translated this to JS.
function attachPinch(wrapperID,imgID)
{
var image = $(imgID);
var wrap = $(wrapperID);
var width = image.width();
var height = image.height();
var newX = 0;
var newY = 0;
var offset = wrap.offset();
$(imgID).hammer().on("pinch", function(event) {
var photo = $(this);
newWidth = photo.width() * event.gesture.scale;
newHeight = photo.height() * event.gesture.scale;
// Convert from screen to image coordinates
var x;
var y;
x -= offset.left + newX;
y -= offset.top + newY;
newX += -x * (newWidth - width) / newWidth;
newY += -y * (newHeight - height) / newHeight;
photo.css('-webkit-transform', "scale3d("+event.gesture.scale+", "+event.gesture.scale+", 1)");
wrap.css('-webkit-transform', "translate3d("+newX+"px, "+newY+"px, 0)");
width = newWidth;
height = newHeight;
});
}
I looked all over the internet, and outernet whatever, until I came across the only working plugin/library - http://cubiq.org/iscroll-4
var myScroll;
myScroll = new iScroll('wrapper');
where wrapper is your id as in id="wrapper"
<div id="wrapper">
<img src="smth.jpg" />
</div>
Not a real answer, but a link to a plug=in that does it all for you. Great work!
https://github.com/timmywil/jquery.panzoom
(Thanks 'Timmywil', who-ever you are)
This is something I wrote a few years back in Java and recently converted to JavaScript
function View()
{
this.pos = {x:0,y:0};
this.Z = 0;
this.zoom = 1;
this.scale = 1.1;
this.Zoom = function(delta,x,y)
{
var X = x-this.pos.x;
var Y = y-this.pos.y;
var scale = this.scale;
if(delta>0) this.Z++;
else
{
this.Z--;
scale = 1/scale;
}
this.zoom = Math.pow(this.scale, this.Z);
this.pos.x+=X-scale*X;
this.pos.y+=Y-scale*Y;
}
}
The this.Zoom = function(delta,x,y) takes:
delta = zoom in or out
x = x position of the zoom origin
y = y position of the zoom origin
A small example:
<script>
var view = new View();
var DivStyle = {x:-123,y:-423,w:300,h:200};
function OnMouseWheel(event)
{
event.preventDefault();
view.Zoom(event.wheelDelta,event.clientX,event.clientY);
div.style.left = (DivStyle.x*view.zoom+view.pos.x)+"px";
div.style.top = (DivStyle.y*view.zoom+view.pos.y)+"px";
div.style.width = (DivStyle.w*view.zoom)+"px";
div.style.height = (DivStyle.h*view.zoom)+"px";
}
function OnMouseMove(event)
{
view.pos = {x:event.clientX,y:event.clientY};
div.style.left = (DivStyle.x*view.zoom+view.pos.x)+"px";
div.style.top = (DivStyle.y*view.zoom+view.pos.y)+"px";
div.style.width = (DivStyle.w*view.zoom)+"px";
div.style.height = (DivStyle.h*view.zoom)+"px";
}
</script>
<body onmousewheel="OnMouseWheel(event)" onmousemove="OnMouseMove(event)">
<div id="div" style="position:absolute;left:-123px;top:-423px;width:300px;height:200px;border:1px solid;"></div>
</body>
This was made with the intention of being used with a canvas and graphics, but it should work perfectly for normal HTML layout

Categories

Resources