Understanding rotation and calculating the top left point in KineticJS - javascript

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

Related

Get started with animated typography/particles in javascript (mapping particles to a word)?

Alright, so I have a good deal of experience with HTML and CSS, and some experience with Javascript (I can write basic functions and have coded in similar languages).
I'm looking to start some visual projects and am specifically interested in getting into particle systems. I have an idea for something similar to Codecademy's name generator here (https://www.codecademy.com/courses/animate-your-name/0/1) where particles are mapped to a word and move if hovered over. It seems as though alphabet.js is what's really behind Codecademy's demo however I can't understand exactly how they mapped the particles to a word, etc.
I've done some basic tutorials just creating rudimentary particles in a canvas but I'm not sure a canvas is the best way to go - demos that utilize one of the many libraries available (such as http://soulwire.github.io/sketch.js/examples/particles.html) don't use a canvas.
So my question is - what is the best way for a beginner/intermediate in Javascript to start with particle systems? Specifically to accomplish the Codecademy name effect or similar? Should I try to use canvas or which library would be best to start with and how would you recommend starting?
The code for this project is achievable for your intermediate JS programmer status.
How the CodeAcademy project works ...
Start by building each letter out of circles and saving each circle's centerpoint in an array. The alphabet.js script holds that array of circle centerpoints.
On mousemove events, test which circles are within a specified radius of the mouse position. Then animate each of those discovered circles radially outward from the mouse position using simple trigonometry.
When the mouse moves again, test which circles are no longer within the specified radius of the current mouse position. Then animate each of those "outside" circles back towards their original positions.
You can also use native html5 canvas without any libraries...
Another approach allowing any text to be "dissolved" and reassembled
Start by drawing the text on the canvas. BTW, this approach will "dissolve" any drawing, not just text.
Use context.getImageData to fetch the opacity value of every pixel on the canvas. Determine which pixels on the canvas contain parts of the text. You can tell if a pixel is part of the text because it will be opaque rather than transparent.
Now do the same procedure that CodeAcademy did with their circles -- but use your pixels:
On mousemove events, test which pixels are within a specified radius of the mouse position. Then animate each of those discovered pixels radially outward from the mouse position using simple trigonometry.
When the mouse moves again, test which pixels are no longer within the specified radius of the current mouse position. Then animate each of those "outside" pixels back towards their original positions.
[Addition: mousemove event to test if circles are within mouse distance]
Note: You probably want to keep an animation frame running that moves circles closer or further from their original positions based on a flag (isInside) for each circle.
function handleMouseMove(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calc the current mouse position
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// test each circle to see if it's inside or outside
// radius of 40px to current mouse position
// circles[] is an array of circle objects shaped like this
// {x:,y:,r:,originalX:,originalY:,isInside:}
var radius=40;
for(var i=0;i<circles.length;i++){
var c=circles[i];
var dx=c.x-mouseX;
var dy=c.y-mouseY;
if(dx*dx+dy*dy<radius*radius){
c.isInside=true;
// move c.x & c.y away from its originalX & originalY
}else{
c.isInside=false;
// if the circle is not already back at it's originalX, originalY
// then move c.x & c.y back towards its originalX, originalY
}
}
}

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

svg.js rotation center of clipped element

Svg.js animation of rotations works great because it uses the center point of the element by default, even when the element is moving from one spot to another, but now I'm having trouble when I add a clipping path to an image, because the center point is still the center of the original image, even if it is outside of the clipping path. I would like to use the center point of the clipping path instead. The closest thing I could find was a question about d3.js.
var rect = draw.rect(60,60)
var picture = draw.image(img.jpg).clipWith(rect)
picture.animate(1000).rotate(360)
How can I get it working in svg.js?
You can pass a centre of rotation to the rotate() method. All you have to do is work out where the centre of the clip rect is and pass that in. It works out to be 90,80.
this.animate(1000).rotate(
360 + currentRotation, 90,80
)
Demo here
For some reason it doesn't work the first time, but after that it works fine. That seems like a bug in svg.js.

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.

Adding parallax to scrolling background

I'm making a canvas game where you travel in a spaceship over an endless repreating background. Right now I'm drawing four instances of the background at different positions based off of the player's x/y position, so they will move with the player.
ctx.translate(ax,ay);
ctx.drawImage(Ibg,Math.round(x/1080)*1080,Math.round(y/720)*720,1080,720);
ctx.drawImage(Ibg,(Math.round(x/1080)*1080)-1080,Math.round(y/720)*720,1080,720);
ctx.drawImage(Ibg,Math.round(x/1080)*1080,(Math.round(y/720)*720)-720,1080,720);
ctx.drawImage(Ibg,(Math.round(x/1080)*1080)-1080,(Math.round(y/720)*720)-720,1080,720);
Translating to ax and ay basically allows objects to scroll with the cameras the player moves, since ax and ay are relative to the player's position. I can create a parallax effect by doing this instead:
ctx.translate(ax*.5,ay*.5);
This makes the background scroll slower than other game objects, like I'd like it to. But I still haven't figured out how to adjust the rest of the code to compensate. As the player moves farther from (0,0) he sees less and less of the background, because it seems to go beyond him at a faster rate. How can I fix this?
As an option to markE's answer you don't need to use a second canvas at all (which is a good option to this).
You can simply use CSS for background image and adjust background position with the amount you need.
Demo here
The essential part is simply these lines:
Background X position where -1 can be replaced with the value you want to move it at.
bgx -= 1;
Then for each loop the background position is updated (Y position is fixed in this example):
canvas.style.backgroundPosition = bgx + 'px -30px'; // set X and Y position
When bgx somehow equals the max width of the image you just reset it to the beginning.
Use 2 canvases -- one placed directly on top of the other
A "background" canvas is on the bottom and animates more slowly.
A "game objects" canvas is on the top and animates more quickly.
That way you can create a parallax effect using different animation speeds for each canvas.

Categories