Image zoom centered on mouse position - javascript

I am writing a script with Fabric.js to zoom an image at the current mouse position. I have made some progress but there is an error somewhere.
Case 1: Keep the mouse at one point and zoom with the mouse wheel.
Result: Works perfectly, image zooms at that particular pixel.
Case 2: Zoom in a little at one position (3-5 times with mouse wheel), then move the mouse to a new position and zoom in there.
Result: Works fine for the first point, but after moving to another point and zooming, the image position is incorrect.
My code is in this fiddle:
https://jsfiddle.net/gauravsoni/y3w0yx2m/1/
I suspect there is something wrong with the image positioning logic:
imgInstance.set({top:imgInstance.getTop()-newMousY,left:imgInstance.getLeft()-newMousX});
What is going wrong?

The key to solving this puzzle is to understand how the image gets enlarged. If we're using a zoom factor of 1.2, the image becomes 20% larger. We assign 1.2 to the variable factor and do the following:
image.setScaleX(image.getScaleX() * factor);
image.setScaleY(image.getScaleY() * factor);
The upper left corner of the image stays in the same place while the picture is enlarged. Now consider the point under the mouse cursor. Every pixel above and to the left of the cursor has become 20% larger. This displaces the point under the cursor by 20% downward and to the right. Meanwhile, the cursor is in the same position.
To compensate for the displacement of the point under the cursor, we move the image so that the point gets back under the cursor. The point moved down and right; we move the image up and left by the same distance.
Note that the image might have been moved in the canvas before the zooming operation, so the cursor's horizontal position in the image is currentMouseX - image.getLeft() before zooming, and likewise for the vertical position.
This is how we calculate the displacement after zooming:
var dx = (currentMouseX - image.getLeft()) * (factor - 1),
dy = (currentMouseY - image.getTop()) * (factor - 1);
Finally, we compensate for the displacement by moving the point back under the cursor:
image.setLeft(image.getLeft() - dx);
image.setTop(image.getTop() - dy);
I integrated this calculation into your demo and made the following fiddle:
https://jsfiddle.net/fgLmyxw4/
I also implemented the zoom-out operation.

Related

how to implement pinch zoom in javascript without using any external library

Does anyone know of a really good Javascript pinch-zooming algorithm?
This is trickier than I had imagined, as you have to scale -AND-
translate to keep the pinch zooming centered between your fingers.
And I want it to do pure translation when the user moves two fingers -
kept an equal distance apart from each other - around the screen,
i.e., this moving two fingers in unison should act like a single-
finger "pan".
scale factor = distance between end point cursor / distance between initial point cursor
distance between start cursor pointer = √((start cursor pointerx2-start cursor pointerx1)^2 * (start cursor pointery2-start cursor pointery1)^2)

How to rotate div in circular motion while counter rotating inner circles?

This image is what I am trying to achieve. Circles on the edges are clickable. Its structure is made such that each rotation will be multiple of 45 deg.
I am using css transform rotate property for rotation.
How is it supposed to work?
When we click on any circle on the edge it should come to its active position and it should always rotate in clockwise direction.
Here is what I did
I achieved rotation by assigning numbers to the circles.
i.e., if clicked on 7 number then it will rotate by angle (9-7)*45=90 degrees.
(This time I did not change the numbers dynamically. i.e., as the circle is rotating the numbers given to the circles are the same.)
This works fine here. But, lets see this scenario: when we click on 2nd position circle it will rotate by 315 deg and then if you click again on the same (second) position then it will make the angle of 270 and it rotates the div in anti-clockwise direction. I think this is its behavior. But, I don't want this to happen. It should rotate again in clockwise direction and should take the active position.
Now to achieve above I did this:
Adding angle with prev angle.
var prev_degree = prev_degree + current_degree;
(current degree is being calculated using the same formula from above.)
This time I changed numbers dynamically i.e., on each click numbers are given to the desired positions. Starting 1 as from Active position till 8 as shown in Image
But this time, when I rotate circle 1, 2 times it rotates perfect then it starts working strange. If you are constantly clicking on the same number then it will add the same angle and will keep rotating perfect no matter what your angle is. If you click on random circles then it wont work which is totally wrong.
Why clockwise?
Because the circles on edges, they contain icon of which I have to maintain position when whole circle rotates.(I can achieve that rotating circles on the edges by assigning negative angles. But, now this is not a problem.)
There is no case when I am getting negative angle.
Let me know if you are not clear with my question.
Please let me know your suggestions to make this work :-)

Understanding rotation and calculating the top left point in KineticJS

I am working on a page where I can view images. I want to create a rotation tool. I've done that, but, it's not working consistently. When I set up the centre point to rotate by, the image jumps slightly, and it gets worse each time. I was experimenting, and, I have code to add a wedge to the top left corner of my top level group ( so, at 0,0 ). If I rotate the image by 45 degrees and drag it so that half of it is off the left edge of my canvas, then I call getAbsolutePosition on the wedge and on the group, I get these values:
layer.getAbsolutePosition()
Object {x: 104.66479545850302, y: 279.2748571151325}
wedge.getAbsolutePosition()
Object {x: 180.2684127179338, y: -73.48773356791764}
I think this means my y position is actually the bottom of the image, which is off screen.
What I want to do, is calculate the absolute position of the middle of my image, when the mouse moves over it, regardless of it's rotation. I have some code that works out points with rotation, which seems like it works at first, almost, but it just gets more and more broken the more I use the tool. I feel like there's something about how Kinetic is tracking these things and what it's reporting, that I am missing. Any hints would be most appreciated. Tutorials I can read are even better ( yes, I've read everything linked from the KineticJS site and searched the web ).
In a nutshell, the question is, if I have an image inside a group, and it's rotated, how do I work out the centre point of the image, taking the rotation in to account, and how do I set the offset so it will rotate from that point, and stay in the same place ?
Thanks
As you've discovered about KinetiJS:
rotation is easy
dragging is easy
dragging+rotation is difficult
After you drag your image you must reset its rotation point (offsetX/offsetY).
KineticJS makes dragging+rotation more difficult than it has to be.
Resetting the offset points of your image will cause KineticJS to automatically move your image (Noooo!!).
That's what's causing your jumping.
The solution to the "jumping" problem:
When you reset the image's rotation point (offsetX/OffsetY) you must also reset the image's X/Y position.
This code resets both XY and Offsets for an image after dragging:
A Demo: http://jsfiddle.net/m1erickson/m9Nw7/
// calc new position and offset
var pos=rect.getPosition();
var size=rect.getSize();
var offset=rect.getOffset();
var newX=pos.x-offset.x+size.width/2;
var newY=pos.y-offset.y+size.height/2;
// reset both position and offset
rect.setPosition([newX,newY]);
rect.setOffset(size.width/2,size.height/2);

Object controll with mouse position relative to circle

Need some inspiration. I've got a picture (blue) and want it to move proportional to the mouse position inside an invisible area (orange). So, if the mouse moves in top-left direction, the image should follow the movement.
I don't want to simply copy the mouse position, rather create an Joystick like behaviour, so if the mouse moves, the image should move stepwise in the desired direction.
But how? I've no idea how to set the right x+y coordinates for the image or how to establish a formula to calculate them.
Incremental (vectored) positions. Consider:
Let's call the dead center of your invisible circle the vector reference point (0,0) or VRP.
You move your mouse away form the VRP. Let's use your image as a reference and say that your mouse is at (-3x -2y) relative to the VRP. You keep it there; It creates a -3 X vector and a -2 Y vector.
For as long as you keep your mouse there, those vectors will be applied to the square's current coordinate at each cycle, like this:
Assume Picture starter position is absolute 100,100.
Cycle 1: [x]:100 -3 = 97;[Y]:100 -2 = 97. New picture position = 97x98y.
Cycle 2: [x]:97 -3 = 94;[Y]:98 -2 = 96. New picture position = 94x96y.
And so forth. If you want to stop the movement, just bring the cursor back to the VRP.
You may sophisticate the mechanism creating acceleration intermediate vectors, or a dead zone around the vector reference point.

Moving a vector "straight out" along a fixed angle

I've searched for the answer to this and have tried many proposed solutions, but none seem to work. I've been struggling with this forever so any insight is greatly appreciated.
I have 3 shapes (vectors I suppose) on a JS canvas, each with an orientation represented as degrees off of 0 and a width. I need to drag one of these shapes "straight out" from its orientation. This is difficult to explain in words so please view the graphic I created:
The middle (diagonal) shape is at 45 degrees. It's origin is the red dot, (x1,y1). The user drags the shape and their mouse lies at the green dot, (x2,y2). Since the shape's origin is in the lower left, I need to position the shape at the position of the lighter blue shape as if the user has dragged straight outward from the shape's origin.
I don't think it matters, but the library I'm using to do this is KineticJS. Here's the code and some information I have available which may help solve the problem. This code positions the shape on top of the mouse, which isn't what I want:
var rotationDeg = this.model.get("DisplayOri"), // rotation in degrees
rotationRadians = rotationDeg * Math.PI / 180, // rotation in rads
unchanged = this.content.getAbsolutePosition(), // {x,y} of the shape before any dragging
dragBoundFunc = function (changed) {
// called on a mouseMove event, so changed is always different and is the x,y of mouse on stage
var delta = {
x: changed.x - unchanged.x,
y: changed.y - unchanged.y
};
return changed; // go to the mouse position
};
[edit] I should mention that the obvious of "return delta" doesn't work.
It sounds like you want to constrain the movement of the object.
Determine the vector representing the constraint axis : that is, we only want motion to occur along this line. It appears from your drawing that this is in the direction of the short line from the red dot out to the left. That vector has a direction of -1/m where m is the slope of the line we are moving.
Constrain the movement. The movement is represented by the mouse move delta - but we only want the portion of that movement in the direction of the constraint axis. This is done with a dot product of the two vectors.
So in pseudo code
m = (line.y2 - line.y1)/(line.x2 - line.x1)
constraintSlope = -1/m
contraintVector = {1, constraintSlope} //unit vector in that direction
userMove = {x2-x1, y2-y1} //vector of mouse move direction
projection = userMove.x * constraintVector.x + userMove.y * constraintVector.y
translation = projection * constraintVector //scaled vector

Categories