Question

I have built a tool in paper.js that allows for the insertion of new control points, which works great, the problem I am running into, is that I must also calculate the handle position for each new control point (unless I am missing something, it does not appear that paper does this for you), and that is proving to be quite the task. The code below is what I currently have working, the point is added with the handles successfully, however it deforms the curve. I want to add the handles in such a way that the curve is not deformed.

gEditor.MoveTool.onMouseDown = function (event) {
    gEditor.HitResult = paper.project.hitTest(event.point, gEditor.HitOptions);

    var location = gEditor.HitResult.location;
    var newPoint = gEditor.HitResult.item.insert(location.index + 1, event.point);
    var prevSegment, nextSegment;

    if (location.index - 1 >= 0){
        prevSegment = gEditor.HitResult.item.segments[location.index - 1];
    }

    if (location.index + 2 < gEditor.HitResult.item.length) {
        nextSegment = gEditor.HitResult.item.segments[location.index + 2];
    }

    if (prevSegment && nextSegment) {
        newPoint.handleIn = {
            x: prevSegment.point.x - ((prevSegment.point.x + newPoint.point.x) / 2),
            y: prevSegment.point.y - ((prevSegment.point.y + newPoint.point.y) / 2),
        };

        newPoint.handleOut = {
            x: nextSegment.point.x - ((nextSegment.point.x + newPoint.point.x) / 2),
            y: nextSegment.point.y - ((nextSegment.point.y + newPoint.point.y) / 2),
        };
    }
}

I have looked at de Cateljau's algorithm, and assume that what I need is some form of this, but I am at a loss as to how to go about implementing it, since every example I have seen basically draws the curve, not finds the X,Y location of the handles.

Was it helpful?

Solution

Yep, paper.js already has this function: curve.divide(). After you've done your hit-test:

path = HitResult.item;
if (HitResult.type == 'stroke') {
   var location = HitResult.location;
   path.curves[location.index].divide(location);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top