Search code examples
svgdiagram

Path starting and ending at same element (looping back)


I'm new to the svg library (HTML5 svg tag and related) and trying to learn. I'm working on a little diagram editor in VueJS using svg. I know how to create a rectangle and even a path from one rectangle/circle/etc to another, but I'm not unclear how to approach creating a path that starts and ends at the same rectangle (i.e., a loop) - something like this

I don't care that much where the start and end points intersect the rectangle, though I'd prefer they were relatively close to one another or at least on the same edge of the rectangle.

Thanks for any nudges in the right direction.


Solution

  • Just create a <path> that consists of a bezier curve whose control points form a rectangle.

    <svg viewBox="0 0 100 100">
    
       <rect x="50" y="10" width="50" height="40" fill="#4472c4"/>
    
       <path d="M 50,20 C 10,20 10,40, 50,40" fill="none" stroke="red"/>
    
       <!-- Show grey lines to indicate the bezier control points -->
       <line x1="50" y1="20" x2="10" y2="20" fill="none" stroke="lightgrey" stroke-width="0.5"/>
       <line x1="50" y1="40" x2="10" y2="40" fill="none" stroke="lightgrey" stroke-width="0.5"/>
    </svg>