dpb - 6 months ago 56

jQuery Question

I have a div (it's a rectangle of course) with an image of a triangle as background. I want to move an image of a circle inside the triangle.

I chose JQuery UI's draggable to use but i couldn't manage to constrain the draggable image within the triangle.

I thought i should use the *containment* option with an array but i can't define a triangle with two coordinates.

Then i found this topic: constrain within a triangle

There the answer is pretty good but it uses a sinus curve and i've got no idea how to define a triangle as the path to use.

Anyone can help how i should constrain the circle's movement to the triangle?

Answer

One of my friends came up with a really simple and nice solution: see it

```
$( "#circle" ).draggable({
drag: function(e, ui) {
var width = $('#triangle').width();
var height = $('#triangle').height();
var x = ui.position.left + $(this).width() / 2;
var y = ui.position.top + $(this).height() / 2;
var difference = Math.abs( x - width / 2 );
var min_y = height * ( difference / (width / 2) );
if ( y < min_y ) y = min_y;
if ( x < 0 ) x = 0;
if ( y < 0 ) y = 0;
if ( x > width ) x = width;
if ( y > height ) y = height;
ui.position.top = y - $(this).height() / 2;
ui.position.left = x - $(this).width() / 2;
}
});
```