Constrain jquery draggable to stay only on the pat

2019-01-26 20:22发布

问题:

So Im trying to make something where the user is able to drag planets along their orbits and it will continuously update the other planets. Ideally I would like this to work with ellipses too.

So far I can drag an image node with jquery and check/change the coordinates, but i cannot update the position reliably while the user is dragging the object. I know there is an axis and a rectangle containment for draggable but this doesn't really help me.

I have a site for calculating planetary orbits http://www.stjarnhimlen.se/comp/ppcomp.html and a formula i think should help me if i can figure out how to constrain the draggable object with coordinate checks Calculating point on a circle's circumference from angle in C#?

But it seems like there should be an easier way to have a user drag a sphere along a circular track while it updates coords for other spheres

here's what i have so far. It's not much

http://jsfiddle.net/b3247uc2/2/

Html

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

Js

 var $newPosX = 100,
    $newPosY = 100;

//create image node
var x = document.createElement("IMG");
x.src = "http://upload.wikimedia.org/wikipedia/commons/a/a4/Sol_de_Mayo_Bandera_Argentina.png";
x.width = 100;
x.height = 100;
x.id = "sun";
x.hspace = 100;
x.vspace = 100;
document.body.appendChild(x);

//coords
var text = document.createTextNode($newPosX + " " + $newPosY);
document.body.appendChild(text);

//make sun draggable and update coords
$("#sun").draggable({
    drag: function (event, ui) {
        $newPosX = $(this).offset().left;
        $newPosY = $(this).offset().top;
    }
});

//0 millisecond update for displayed coords
setInterval(check, 0);

function check() {
    //tries to constrain movement, doesn't work well
    /*
    if ($newPosX > 300) {
        $("#sun").offset({
            left: 200
        });
    }
    */
    text.nodeValue = ($newPosX + " " + $newPosY);
}

Edit: I found this and am trying to modify it to suit my purposes but have so far not had luck. http://jsfiddle.net/7Asn6/

Ok so i got it to drag

http://jsfiddle.net/7Asn6/103/

This is pretty close to what I want but can be moved without being clicked on directly

http://jsfiddle.net/7Asn6/104/

Ok final edit on this question. This one seems to work well and have fixed my problems. I would still very much like to hear peoples implementation ideas or ideas to make it work smoother.

http://jsfiddle.net/7Asn6/106/