Skip to content Skip to sidebar Skip to footer

Constrain Within A Triangle

I am looking for a generic piece of code (javascript) that would work with jquery UI to constrain movement(drag) of a div within an triangle. similar to this (http://stackoverflow.

Solution 1:

See this answer which shows how to constrain a jquery draggable to an arbitrary path.

The trick is to alter the ui.position variables within the drag event, to constrain the movement.

Solution 2:

Since none of the given answers actually show how to constrain a draggable to a triangular area, I thought I'd share this jsfiddle which demonstrates an actual working example.

I think the key here is not to focus so much on the "triangle" aspect but more importantly to realize a triangle is a polygon. This allows us to address the issue head-on using many existing algorithms that relate to a point and a polygon.

This 2D Graph library JavaScript 2D Graph Library provides all the tools we need to solve this problem. Mainly, each Shape has an associated function constrain which will constrain a Point to the inner area of a the Shape (the edge included) via a LineSegment that connects to the centroid of the Shape. (It also looks like you can set the center point for the Shape as a second argument which would prove handy for concave Polygon's.)

This jsFiddle Triangle Constraint via jQuery UI Draggable uses the jQuery UI Draggable drag callback in conjunction with the Graph library to do the constraint. It actually uses the coordinates of the SVG Polygon to construct the Graph Polygon only inverting the y-axis to switch between screen and Cartesian coordinates.

The set-up that takes place in document ready is fairly simple:

var points = $('polygon').attr('points').trim().split(' ').map(function(vertex) { var coordinates = vertex.split(','); returnnew aw.Graph.Point(Number(coordinates[0]), Number(-coordinates[1])); }),
    triangle = new aw.Graph.Polygon(points);
$('.map-selector').draggable({
    containment: '.map',
    drag: function (event, ui) {
        var left = ui.position.left, top = -ui.position.top;
        var constrained = triangle.constrain(new aw.Graph.Point(left, top));
        ui.position.left = constrained.x; ui.position.top = -constrained.y;
    }
});

Cheers!

Post a Comment for "Constrain Within A Triangle"