svgpathtools

repository·master·Indexed 20 days ago

https://github.com/mathandy/svgpathtools

A Python library for the manipulation, analysis, and transformation of SVG Path objects and Bézier curves. It provides tools for SVG I/O, geometric computations such as intersection and arc length calculation, path smoothing, and Bézier analysis including conversion to numpy.poly1d objects. The library supports Line, Arc, QuadraticBezier, and CubicBezier segments.

Tokens
2.4K
Snippets
12
Records
15
Agent score
21%

What's inside svgpathtools

  1. Overview of svgpathtools features

    master

    svgpathtools

    svgpathtools is a collection of tools for manipulating and analyzing SVG Path objects and Bézier curves.

    Key Capabilities

    • SVG I/O: Read, write, and display SVG files containing Path and other SVG elements.
    • Bézier Analysis:
      • Convert Bézier path segments to numpy.poly1d (polynomial) objects.
      • Convert polynomials (in standard form) to their Bézier form.
      • Compute tangent vectors, normal vectors, and curvature.
    • Path Manipulation:
      • Break discontinuous paths into continuous subpaths.
      • Reverse segment/path orientation.
      • Crop and split paths and segments.
      • Smooth paths to make them differentiable.
    • Geometric Computation:
      • Compute intersections between paths and/or segments.
      • Find bounding boxes for paths or segments.
      • Compute area enclosed by a closed path.
      • Compute arc length and inverse arc length.
    • Domain Mapping: Transition maps from path domain to segment domain and back (T2t and t2T).
    • Color Conversion: Convert RGB color tuples to hexadecimal color strings and vice versa.
    • General Bézier Curves: The bezier.py submodule provides tools for working with nth order Bézier curves stored as n-tuples.
  2. How the Path class works

    master

    A Path object is a mutable sequence of path segment objects. It behaves similarly to a Python list, allowing you to use standard methods like .append(), .insert(), .pop(), and slicing.

    Key properties and methods:

    • .iscontinuous(): Returns True if the segments are connected.
    • .isclosed(): Returns True if the path starts and ends at the same point.
    • .continuous_subpaths(): A workaround for handling discontinuous paths.
    • .d(): Returns the SVG path data string (d-string) for the path.
    from svgpathtools import Path, Line, CubicBezier
    
    path = Path(CubicBezier(300+100j, 100+100j, 200+200j, 200+300j), Line(200+300j, 250+350j))
    path.append(CubicBezier(250+350j, 275+350j, 250+225j, 200+100j))
    print(path.iscontinuous())
    print(path.d())
  3. Install svgpathtools from source

    master

    If you prefer to install from a local clone of the repository, navigate to the folder containing setup.py and run the installation command.

    $ python setup.py install
  4. Migrating from svg.path (v2.0) to svgpathtools

    master

    If you are migrating from svg.path (v2.0), note the following breaking changes:

    1. Arc Attribute Renaming: The Arc.arc attribute has been renamed to Arc.large_arc.
    2. Path.d() Formatting: To achieve behavior similar to svg.path (v2.0), you must set both useSandT and use_closed_attrib to True.

    Note: While setting these flags makes the behavior identical, svgpathtools uses default float formatting instead of the General format ({:G}) used in svg.path to provide increased precision in the resulting d-string.

  5. Access points using parameterization (.point())

    master

    All path segments and Path objects can be parameterized over the domain $0 \le t \le 1$.

    • .point(t): Returns the $(x, y)$ coordinate at parameter $t$. For segments, $t$ is the local parameter. For Path objects, $t$ is the global parameter.
    • Path.T2t(T): Converts a global path parameter $T$ into a tuple of (segment_index, local_t).
    • Path.t2T(t): The inverse of T2t.
    from svgpathtools import parse_path
    
    path = parse_path('M 300 100 C 100 100 200 200 200 300 L 250 350')
    # Get point at 50% of the total path length
    print(path.point(0.5))
    
    # Find which segment contains the point at global parameter 0.5
    k, t = path.T2t(0.5)
    print(f"Segment {k} at local parameter {t}")
  6. Calculate tangents, normals, and derivatives

    master

    You can compute geometric properties of path segments at any parameter $t$:

    • .unit_tangent(t): Returns the unit tangent vector at $t$.
    • .normal(t): Returns the normal vector at $t$.
    • .derivative(t): Returns the derivative at $t$.
    • .reversed(): Returns a new segment with the orientation reversed.
    from svgpathtools import CubicBezier
    
    b = CubicBezier(300+100j, 100+100j, 200+200j, 200+300j)
    t = 0.5
    
    tangent = b.unit_tangent(t)
    normal = b.normal(t)
  7. Find intersections between paths

    master

    The .intersect(other_path) method finds all points where two paths intersect. It returns an iterator yielding tuples of (T1, segment1, t1, T2, segment2, t2), where $T$ is the global parameter and $t$ is the local segment parameter.

    from svgpathtools import parse_path
    
    path1 = parse_path('M 0 0 L 100 100')
    path2 = parse_path('M 0 100 L 100 0')
    
    for (T1, seg1, t1, T2, seg2, t2) in path1.intersect(path2):
        print(f"Intersection at: {path1.point(T1)}")
  8. Calculate arc length and inverse arc length

    master

    To work with distances along a curve rather than the parameter $t$:

    • .length(): Returns the total length of the segment/path.
    • .ilength(distance): The inverse length function. Given a distance $d$ along the curve, it returns the parameter $t$ such that the distance from the start to $t$ is $d$.
    from svgpathtools import Line
    
    seg = Line(0, 10)
    total_len = seg.length()
    # Find the parameter t at the halfway point of the length
    t_mid = seg.ilength(total_len / 2)
    print(seg.point(t_mid))
  9. Read SVG files with svg2paths() and svg2paths2()

    master

    To convert an SVG file into usable Python objects:

    • svg2paths(filename): Returns a list of Path objects and a list of dictionaries containing path attributes.
    • svg2paths2(filename): A convenience function that also returns svg_attributes (the attributes of the SVG element itself).

    These functions support Line, Polyline, Polygon, and Path SVG elements.

    from svgpathtools import svg2paths2
    
    paths, attributes, svg_attributes = svg2paths2('test.svg')
    first_path = paths[0]
    print(first_path)
    print(attributes[0]['stroke'])