Search code examples
javascriptpathdrawingpaperjs

PaperJS: stop drawing path when crossing a previous path


I am using paperjs, when the user draws a line I want it to stop when it crosses a previously drawn line. This my current test code:

tool.minDistance = 1;

var path;
var drawing = false;

function onMouseDown(event) {
    if (!drawing) {
        startLine(event);
        drawing = true;
    }
}

function onMouseDrag(event) {
    if (drawing) {
        path.add(event.point);
    }
}

function onMouseUp(event) {
    if (drawing) {
        endLine(event);
    }
}

function startLine(event) {
    path = new Path();
    path.strokeColor = 'black';
    path.strokeWidth = 10;
    path.strokeCap = 'round';
    path.add(event.point);
}

function endLine(event) {
    path.add(event.point);
    path.smooth();
    path.simplify();
    path.onMouseDrag = function(event) {
        if (drawing) {
            console.log('ending line')
            endLine(event);
        }
    }
    drawing = false;
}

I have added an onMouseDrag event to detect when the user crosses an existing path. This works most of the time, but sometimes it is not triggered, especially when drawing slowly.

My question is why is the onMouseDrag event not triggered in that situation? And/or is there a better way to accomplish what I am trying to do?


Solution

  • A better way is to use Path.getIntersections

    When you draw use it to get intersections with drawn paths. If it return somethings, stop to draw at the point of intersection.

    See also Path.getCrossings