Search code examples
javascriptsvgvector-graphicssnap.svg

Obtaining rendered borders of a crooked svg-object


I need to know whether an svg-object is adjacent to another one or not. Therefore I need to get its borders. Those objects can be a rect or a path. This is fairly easy when they are straight, but I don't know how to do this when they're curved or crooked.

An example of what I mean can be found here or a short example here:

<svg id="mysvg" xmlns="http://www.w3.org/2000/svg" viewBox="0 200 512 512">
   <path d="m 223.40414,282.21605 35.53211,-3.88909 0,-18.73833 -19.79899,-0.17678 c -5.83251,7.19542 -10.70707,15.0451 -15.73312,22.8042 z" id="pB"></path>
</svg> 

If I use the Box corners, I create a virtual straight rectangular, which adjacent objects are not equal to the adjacents of the rendered object. How can I do that?


Solution

  • The Snap library offers some nice utilities for your problem. Your question does not define what "adjacent" should really mean. Here is a function that sets a threshold for the maximal distance between to paths:

    var threshold = 1;
    
    function isAdjacent (id1, id2) {
        var s = Snap("#mysvg");
        var first = s.select('#' + id1);
        var second = s.select('#' + id2);
    
        var len = first.getTotalLength(first);
    
        var p1, p2;
        for (var at = 0; at <= len; at += threshold) {
            p1 = first.getPointAtLength(at);
            if ( Snap.closestPoint(second, p1.x, p1.y).distance <= threshold) {
                return true;
            }
        }
        return false;
    }
    

    JsFiddle