lukemh lukemh - 1 month ago 6x
Javascript Question

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 ( but a triangle, and not a circle.

I would prefer the triangle to be defined as a rapheal svg like this...

(function() {
Raphael.fn.triangle = function (cx, cy, r) {
r *= 1.75;
return this.path("M".concat(cx, ",", cy, "m0-", r * .58, "l", r * .5, ",", r * .87, "-", r, ",0z"));

var paper = Raphael(document.getElementById("triangle"), "100%", "100%");
var triangle = paper.triangle(100,100,90);
triangle.attr("fill", "#444444");
triangle.attr("stroke", "#444444");

$( "#draggable" ).draggable({ containment: "#triangle svgnode", scroll: false });

looking forward to solutions.

I would like to note that the draggable element could also be a svg node if that is easier.


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.