### Define and Apply Colors Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows how to define colors using various formats including XHTML names, hex codes (3, 4, 6, and 8 digits), and RGB strings (percentage or numerical). Example demonstrates setting stroke color for a Circle. ```python >>> Circle(stroke="yellow") Circle(center=Point(0,0), r=1, stroke="#ffff00") ``` -------------------------------- ### Create Invalid SVG Path with Close Command Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows an example of creating an invalid SVG path where a Close command does not connect back to the starting point. It then demonstrates how to retrieve the path's 'd' attribute, which will reflect the invalid structure. ```python wrong = Path(Line(100+100j,200+100j), Close(200+300j, 0)) print(wrong.d()) ``` -------------------------------- ### Matrix Order of Operations for Transformations Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates the critical importance of the order of operations when combining multiple transformations (e.g., scale and translate) using Matrix objects. The examples demonstrate how different orders yield different results when applied to points. ```python >>> Point(100,100) * (Matrix("scale(2)") * Matrix("Translate(40,40)")) Point(240,240) >>> Point(100,100) * (Matrix("Translate(40,40)") * Matrix("scale(2)")) Point(280,280) >>> (Matrix("scale(2)") * Matrix("Translate(40,40)")) Matrix(2, 0, 0, 2, 40, 40) >>> (Matrix("Translate(40,40)") * Matrix("scale(2)")) Matrix(2, 0, 0, 2, 80, 80) >>> Point(100,100) * Matrix("Matrix(2,0,0,2,80,80)") Point(280,280) ``` -------------------------------- ### SimpleLine Transformations and Path Data Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates the creation of SimpleLine objects, applying transformations using string-based SVG attributes, and converting them to path data. It also shows how to get the absolute path data after transformations. ```python from svgelements import * s = SimpleLine(0,0,200,200) print(s) # Output: SimpleLine(x1=0.0, y1=0.0, x2=200.0, y2=200.0) s *= "rotate(45)" print(s) # Output: SimpleLine(x1=0.0, y1=0.0, x2=200.0, y2=200.0, transform=Matrix(0.707106781187, 0.707106781187, -0.707106781187, 0.707106781187, 0, 0)) print(abs(s)) # Output: SimpleLine(x1=0.0, y1=0.0, x2=2.842170943040401e-14, y2=282.842712474619, stroke='None', fill='None') print(s.d()) # Output: 'M 0,0 L 2.84217094304E-14,282.842712475' ``` -------------------------------- ### Write SVG with Rect Element to File Source: https://github.com/meerk40t/svgelements/blob/master/README.md Creates an SVG file containing a rectangle element. This example shows how to append elements to an SVG object and then write the SVG to a file. The output includes the SVG header and the rect element. ```python s = SVG() s.append(Rect(0,0,"2in", "2in")) s.write_xml("rect.svg") ``` -------------------------------- ### Write Empty SVG to File Source: https://github.com/meerk40t/svgelements/blob/master/README.md Writes an empty SVG structure to a specified file. This is a basic example demonstrating the file writing capability of the library. The resulting file will contain a minimal SVG header. ```python >>> SVG().write_xml("empty.svg") ``` -------------------------------- ### Path Object Transformations with Matrix Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows how Path objects can be directly multiplied by Matrix objects to apply transformations such as scaling and rotation. Examples include transforming a Path with lines and modifying an SVG path string. ```python >>> Path(Line(0+0j, 100+100j)) * Matrix.scale(2) Path(Line(start=Point(0,0), end=Point(100,100)), transform=Matrix(2, 0, 0, 2, 0, 0), stroke='None', fill='None') >>> Path("M0,0L100,100") * Matrix.rotate(30) Path(Move(end=Point(0,0)), Line(start=Point(0,0), end=Point(100,100)), transform=Matrix(0.154251449888, -0.988031624093, 0.988031624093, 0.154251449888, 0, 0)) >>> str(Path("M0,0L100,100") * Matrix.rotate(30)) 'M 0,0 L 114.228,-83.378' ``` -------------------------------- ### Write SVG Files (Python) Source: https://context7.com/meerk40t/svgelements/llms.txt Shows how to create and write SVG content to files using the svgelements library. Covers creating basic shapes like Rect, Circle, and Path, appending them to an SVG object, and writing to .svg or .svgz files. Also demonstrates getting XML as a string and handling transformations. ```python from svgelements import * # Create SVG structure svg = SVG() svg.append(Rect(0, 0, "2in", "2in", fill='red', stroke='black')) svg.append(Circle(cx="3in", cy="1in", r="0.5in", fill='blue')) svg.append(Path("M 0,0 L 100,100 L 100,0 z", stroke='green', fill='yellow')) # Write to file svg.write_xml("output.svg") # Write compressed SVGZ svg.write_xml("output.svgz") # Get XML as string xml_string = svg.string_xml() # Write individual elements group = Group(id="my-group") group.append(Circle(r=10)) group.append(Rect(0, 0, 20, 20)) group_xml = group.string_xml() # Output: '' # Preserve transformations in output rect = Rect(10, 10, 50, 30) rect *= Matrix("rotate(45)") print(rect.string_xml()) # Includes transform attribute with matrix ``` -------------------------------- ### Handle Lengths and Units Source: https://context7.com/meerk40t/svgelements/llms.txt Provides examples for parsing Length objects from strings with various units (mm, cm, in, pt, px, %). It demonstrates converting lengths between different units and using them with shapes and transformations, including CSS length transforms for matrices and points. ```python from svgelements import * # Parse lengths with units length = Length('25mm') length = Length('2.54cm') length = Length('1in') length = Length('72pt') length = Length('96px') length = Length('10%') # Convert to different units inches = Length('25mm').in_inches() # 0.9842525 pixels = Length('1in').value(ppi=96) # 96.0 mm = Length('1in').in_mm() # 25.4 # Use with shapes and transformations rect = Rect('1cm', '1cm', '5cm', '3cm') # CSS length transforms matrix = Matrix("translate(1cm, 1cm)") matrix.render(ppi=96.0) # Convert to pixel values point = Point(0, 0) * matrix # Point(37.795296, 37.795296) ``` -------------------------------- ### Iterate and Process SVG Elements Source: https://github.com/meerk40t/svgelements/blob/master/README.md The `elements()` method on an SVG object flattens all child elements for ordered processing. This example demonstrates iterating through elements, skipping hidden ones, and appending specific types (SVGText, Path, Shape, SVGImage) to a list after potential reification or loading. ```python for element in svg.elements(): try: if element.values['visibility'] == 'hidden': continue except (KeyError, AttributeError): pass if isinstance(element, SVGText): elements.append(element) elif isinstance(element, Path): if len(element) != 0: elements.append(element) elif isinstance(element, Shape): e = Path(element) e.reify() # In some cases the shape could not have reified, the path must. if len(e) != 0: elements.append(e) elif isinstance(element, SVGImage): try: element.load(os.path.dirname(pathname)) if element.image is not None: elements.append(element) except OSError: pass ``` -------------------------------- ### SVG Color Parsing and Manipulation Source: https://github.com/meerk40t/svgelements/blob/master/README.md Handles various SVG color formats (hex, rgb, named colors, hsl) and converts them to a consistent RGBA integer representation. Supports operations like getting color components (red, green, blue) and calculating distances between colors. ```python from svgelements import Color # Example usage: print(Color("red").hex) print(Color('red').red) print(Color('hsl(120, 100%, 50%)')) c = Color('hsl(120, 100%, 50%)') c.blue = 50 print(c) print(Color.distance('red', 'lightred')) print(Color.distance('red', 'blue')) print(Color('red').distance_to('blue')) ``` -------------------------------- ### Create and Compare SVG Paths Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates creating SVG paths using different string formats and comparing them for equality. It also shows how to construct a path from individual segment objects. ```python path1 = Path('M 100 100 L 300 100 L 200 300 z') path2 = Path('M100,100L300,100L200,300z') print(path1 == path2) path3 = Path(Move(100 + 100j), Line(100 + 100j, 300 + 100j), Line(300 + 100j, 200 + 300j), Close(200 + 300j, 100 + 100j)) print(path1 == path3) ``` -------------------------------- ### Initializing Path from Path Data String Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates the preferred method of initializing a Path object directly from a path data string, which is more readable and direct than providing segments individually. ```python from svgelements import Path path_data = 'M 100 100 L 300 100' path_object = Path(path_data) print(path_object) ``` -------------------------------- ### Path Scaling and Bounding Box Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates applying scaling transformations to a Path object and calculating its bounding box. This is useful for transformations and layout calculations. ```python from svgelements import Path path_obj = Path("M0,0v1h1v-1z") scaled_path = path_obj * "scale(20)" print(scaled_path.bbox()) ``` -------------------------------- ### Polygon and Polyline Transformations and Path Data Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates the creation of Polygon and Polyline objects, applying scaling transformations, and generating their respective path data. It also shows how a Polyline can be converted to a closed Polygon. ```python from svgelements import * p_polygon = Polygon(0,0, 100,0, 100,100, 0,100) p_polygon *= "scale(2)" print(p_polygon.d()) # Output: 'M 0,0, L 200,0, L 200,200, L 0,200 Z' p_polyline = Polyline(0,0, 100,0, 100,100, 0,100) p_polyline *= "scale(2)" print(p_polyline.d()) # Output: 'M 0,0, L 200,0, L 200,200, L 0,200' polyline_closed = Path(Polyline((20,0), (10,10), 0)) + "z" polygon_equivalent = Polygon("20,0 10,10 0,0") print(polyline_closed == polygon_equivalent) # Output: True ``` -------------------------------- ### Path Initialization from SVG String Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates creating a Path object directly from an SVG path data string. This is a concise way to define path geometry. ```python from svgelements import Path path_string = "M0,0v1h1v-1z" path_obj = Path(path_string) print(path_obj) ``` -------------------------------- ### Matrix Transformations and CSS Compatibility Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates the use of the Matrix class for transformations like translate, scale, and skew, showcasing compatibility with SVG 1.1, SVG 2.0, and CSS functions. It also illustrates handling different unit types and the importance of rendering matrices before use. ```python >>> Point(0,0) * Matrix("Translate(1cm,1cm)") Point('1cm','1cm') >>> Point(0,0) * (Matrix("Translate(1cm,1cm)").render(ppi=96.0)) Point(37.795296,37.795296) >>> Point(10,0) * Matrix("Rotate(1turn)") Point(10,-0) >>> Point(10,0) * Matrix("Rotate(400grad)") Point(10,-0) >>> Point(10,0) * Matrix("Rotate(360deg)") Point(10,-0) ``` -------------------------------- ### Point Transformation with Matrix Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates applying a matrix transformation (rotation) to a Point object. The Point class can accept various initial definitions and be manipulated by matrix objects or transform strings. ```python >>> Point(10,10) * "rotate(90)" Point(-10,10) ``` -------------------------------- ### Create and Transform Line Segment Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates the creation of a `Line` segment and its transformation using rotation. This involves the `Line`, `Matrix`, and `Angle` classes. Transformations can be applied directly using matrix multiplication. ```python from svgelements import Line, Matrix, Angle line = Line((20, 20), (40, 40)) rotated_line = line * Matrix.rotate(Angle.degrees(45)) print(rotated_line) ``` -------------------------------- ### Apply Matrix Transformations to Paths Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows how to apply matrix transformations to `Path` objects using string representations of transformations or `Matrix` objects. This includes rotation and scaling. The `*` operator is used for applying transformations. ```python from svgelements import Path, Matrix path = Path("L 40,40") rotated_path = path * "Rotate(45)" print(rotated_path) scaled_path = Path("M1,1 1,2 2,2 2,1z") * "scale(2)" print(scaled_path) ``` -------------------------------- ### Create and Manipulate Path Objects Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates the creation of Path objects and their manipulation by appending SVG path data strings. Paths represent sequences of segments that define shapes. ```python >>> Path() + "M0,0z" Path(Move(end=Point(0,0)), Close(start=Point(0,0), end=Point(0,0))) ``` -------------------------------- ### Viewbox and Unit Scaling in Svgelements Source: https://github.com/meerk40t/svgelements/blob/master/README.md Explains the role of the Viewbox object in handling SVG viewport scaling and unit conversions. It highlights how Viewbox.transform() generates equivalent transformations based on SVG specifications, including preserveAspectRatio and meetOrSlice. ```python # Viewbox objects have a call to `.transform()` which will provide the string for an equivalent transformation for the given viewbox. # The `Viewbox.transform()` code conforms to the algorithm given in SVG 1.1 7.2, SVG 2.0 8.2 'equivalent transform of an SVG viewport.' # This will also fully implement the `preserveAspectRatio`, `xMidYMid`, and `meetOrSlice` values for the viewboxes. ``` -------------------------------- ### Define and Parse Length Units Source: https://github.com/meerk40t/svgelements/blob/master/README.md Explains the use of Length objects for defining linear space and demonstrates parsing various units like centimeters, millimeters, inches, and creating Length objects from strings. ```python Length('200mm') ``` -------------------------------- ### Generating SVG Path Data (d() method) Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows how to use the d() method of a Path object to generate its SVG representation. It also demonstrates generating relative path data. ```python from svgelements import Path, Line, QuadraticBezier, Move path = Path(Move(100+100j), Line(100+100j,300+100j), QuadraticBezier(300+100j, 200+200j, 200+300j)) print(path.d()) print(path.d(relative=True)) ``` -------------------------------- ### Rectangles with Path Data Conversion Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates how to create Rect objects, generate their SVG path data using the .d() function, and manipulate them with transformations. It shows how these transformations can be applied directly to Rect objects or used to create Path objects. ```python from svgelements import * rect = Rect(10, 10, 8, 4) print(rect.d()) # Output: 'M 10,10 L 18,10 L 18,14 L 10,14 Z' path_data = rect.d() path = Path(path_data) rotated_path = path * "rotate(0.5turns)" print(rotated_path) # Output: M -10,-10 L -18,-10 L -18,-14 L -10,-14 Z rotated_rect = rect * "rotate(0.5turns)" print(rotated_rect) # Output: Rect(x=10, y=10, width=8, height=4, transform=Matrix(-1, 0, -0, -1, 0, 0), stroke='None', fill='None') print(rotated_rect.d()) # Output: 'M -10,-10 L -18,-10 L -18,-14 L -10,-14 L -10,-10 Z' # Rectangles with rounded corners rounded_rect = Rect(10, 10, 8, 4, 2, 1) print((rounded_rect * "rotate(0.25turns)").d()) # Output: 'M -10,12 L -10,16 A 2,1 90 0,1 -11,18 L -13,18 A 2,1 90 0,1 -14,16 L -14,12 A 2,1 90 0,1 -13,10 L -11,10 A 2,1 90 0,1 -10,12 Z' print((rounded_rect * "rotate(0.25turns)").d(relative=True)) # Output: 'm -10,12 l 1.77636E-15,4 a 2,1 90 0,1 -1,2 l -2,0 a 2,1 90 0,1 -1,-2 l -1.77636E-15,-4 a 2,1 90 0,1 1,-2 l 2,0 a 2,1 90 0,1 1,2 z' ``` -------------------------------- ### Work with Points Source: https://context7.com/meerk40t/svgelements/llms.txt Demonstrates creating Point objects from various inputs (tuples, lists, strings, complex numbers), accessing coordinates, performing point arithmetic, calculating distances and angles between points, and using polar coordinates. It also covers point reflection and transformation. ```python from svgelements import * # Create points from various inputs point = Point(10, 20) point = Point((10, 20)) point = Point([10, 20]) point = Point("10, 20") point = Point(10 + 20j) # Complex number # Access coordinates x = point.x y = point.y x = point[0] y = point[1] x = point.real y = point.imag # Point arithmetic and operations distance = point.distance_to([0, 0]) # Euclidean distance angle = point.angle_to([100, 100]) # Angle to another point midpoint = point.move_towards([100, 100], 0.5) # Move 50% toward target # Polar coordinates destination = Point(0, 0).polar_to( Angle.turns(0.125), Length("5cm").value(ppi=96) ) # Point at angle with distance # Reflection (for smooth bezier curves) reflected = point.reflected_across([50, 50]) # Transform points transformed = Point(100, 100) * Matrix("rotate(45deg)") ``` -------------------------------- ### Ellipse and Circle Equivalency Check Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows how to create Ellipse and Circle objects and check for their equivalency. A Circle is treated as a specific case of an Ellipse with equal rx and ry. ```python from svgelements import * ellipse = Ellipse(center=(0,0), rx=10, ry=10) circle = Circle(center="0,0", r=10.0) print(ellipse == circle) # Output: True ``` -------------------------------- ### Combine Shapes and Query Properties Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates combining different SVG shapes like `Circle` and `Rect` using the `+` operator. The combined object's bounding box and length can then be queried. ```python from svgelements import Circle, Rect combined_shape_bbox = (Circle() + Rect()).bbox() print(combined_shape_bbox) combined_shape_length = (Circle() + Rect()).length() print(combined_shape_length) ``` -------------------------------- ### Calculating Path Segment Length Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates calculating the length of various path segments, including CubicBezier. For complex segments like CubicBezier and Arc, length calculation can be computationally intensive and accepts an 'error' parameter for approximation. ```python from svgelements import CubicBezier cubic_bezier_segment = CubicBezier(300+100j, 100+100j, 200+200j, 200+300j) length = cubic_bezier_segment.length(error=1e-5) print(length) ``` -------------------------------- ### Parse SVG Data with svgelements Source: https://github.com/meerk40t/svgelements/blob/master/README.md The `parse` function takes SVG source data and optional parameters to configure parsing, such as PPI, dimensions, color, and transforms. It returns an SVG object, resolving structural elements like and , and converting properties like fill and stroke to appropriate types. `reify` controls whether transforms are applied, `ppi` affects physical unit conversions, and `width`/`height` define the SVG view size. `color` handles `currentColor` fallback, and `transform` allows prepending matrices. `context` is for nested SVG contexts. ```python def parse(source, reify=True, ppi=DEFAULT_PPI, width=1, height=1, color="black", transform=None, context=None): ``` -------------------------------- ### Apply Matrix Transformations with svgelements Source: https://context7.com/meerk40t/svgelements/llms.txt Shows how to create and apply matrix transformations to SVG elements using the `svgelements` library. It covers creating basic transformation matrices (translate, scale, rotate, skew), parsing matrices from SVG/CSS strings, applying transformations via matrix multiplication, transforming points, and chaining multiple transformations. ```python from svgelements import * # Create transformation matrices translate = Matrix.translate(50, 100) scale = Matrix.scale(2) rotate = Matrix.rotate(Angle.degrees(45)) skew_x = Matrix.skew_x(Angle.degrees(15)) # Parse from SVG/CSS transform strings matrix = Matrix("rotate(45)") matrix = Matrix("scale(2) translate(10,20)") matrix = Matrix("rotate(0.25turn, 100, 100)") # Rotate around point # Apply transformations using multiplication path = Path("M0,0 L100,0 L100,100 L0,100 z") transformed = path * Matrix("scale(2)") print(transformed.d()) # Output: M 0,0 L 200,0 L 200,200 L 0,200 Z # Transform with CSS angles rotated = path * "rotate(90deg)" rotated = path * "rotate(0.25turn)" rotated = path * "rotate(100grad)" # Chain transformations (order matters!) matrix1 = Matrix("scale(2)") * Matrix("translate(40,40)") # Scale then translate matrix2 = Matrix("translate(40,40)") * Matrix("scale(2)") # Translate then scale # matrix1 = Matrix(2, 0, 0, 2, 40, 40) # matrix2 = Matrix(2, 0, 0, 2, 80, 80) # Transform points point = Point(100, 100) * Matrix("scale(2)") # Point(200, 200) ``` -------------------------------- ### Query Path Segment Properties (Python) Source: https://context7.com/meerk40t/svgelements/llms.txt Demonstrates querying properties of SVG path segments like Line, Arc, CubicBezier, and QuadraticBezier. Includes calculating points at a given t value, segment length, bounding boxes, reversing segments, checking for smoothness, and combining segments. ```python from svgelements import * # Create individual segments line = Line(start=(0, 0), end=(100, 100)) arc = Arc(start=(0, 0), radius=50+50j, rotation=0, arc=0, sweep=1, end=(100, 0)) cubic = CubicBezier(start=(0, 0), control1=(25, 50), control2=(75, 50), end=(100, 0)) quad = QuadraticBezier(start=(0, 0), control=(50, 50), end=(100, 0)) # Query point at position t (0.0 to 1.0) midpoint = line.point(0.5) quarter_point = cubic.point(0.25) # Calculate segment length line_length = line.length() # Exact quad_length = quad.length() # Exact cubic_length = cubic.length(error=1e-5) # Approximation with error tolerance arc_length = arc.length() # Exact with scipy, otherwise approximation # Get bounding box bbox = cubic.bbox() # (x_min, y_min, x_max, y_max) # Reverse segment direction reversed_line = line.reverse() # Check if segments are smooth continuations path = Path('M100,200 C100,100 250,100 250,200 S400,300 400,200') segment1 = path[1] # First cubic bezier segment2 = path[2] # Smooth cubic bezier is_smooth = segment2.is_smooth_from(segment1) # True # Combine segments into paths path = Move((0, 0)) + Line((0, 0), (100, 0)) + Close() print(path.d()) # 'M 0,0 L 100,0 Z' ``` -------------------------------- ### Path Manipulation with Segments Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates how to create, append, replace, delete, and combine Path segments. The Path object acts as a mutable list, allowing dynamic modification of path data. ```python from svgelements import Path, Line, QuadraticBezier, Move path = Path(Line(100+100j,300+100j), Line(100+100j,300+100j)) print(path) path.append(QuadraticBezier(300+100j, 200+200j, 200+300j)) print(path) path[1] = Line(200+100j,300+100j) print(path) del path[1] print(path) path = Move() + path print(path) ``` -------------------------------- ### Combine Path Segments Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates combining individual path segments like `Move` and `Line` into a `Path` object using the `+` operator. It also shows how to print the SVG path data (`d` attribute) for a combined path. ```python from svgelements import Path, Move, Line, Close combined_path = Move((20,20)) + Line((20,20), (40,40)) print(combined_path) path_d = (Move((2,2)) + Close()).d() print(path_d) ``` -------------------------------- ### Manipulate SVG Path and Append Segments Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates how to manipulate SVG paths by appending new segments, such as a QuadraticBezier curve. It also shows how to slice a path and check the length of a sub-path. ```python path1 = Path('M 100 100 L 300 100 L 200 300 z') path1.append(QuadraticBezier(300+100j, 200+200j, 200+300j)) print(len(path1[2:]) == 3) ``` -------------------------------- ### Query Path Bounding Box Source: https://github.com/meerk40t/svgelements/blob/master/README.md Retrieves the bounding box of path elements, both in their original and transformed coordinate systems. The `bbox()` method can take a `transformed` argument to specify the coordinate system. ```python from svgelements import Path, QuadraticBezier bezier_bbox = QuadraticBezier("0,0", "50,50", "100,0").bbox() print(bezier_bbox) transformed_bbox = (Path('M 0,0 Q 50,50 100,0') * "translate(40,40)").bbox() print(transformed_bbox) untransformed_bbox = (Path('M 0,0 Q 50,50 100,0') * "translate(40,40)").bbox(transformed=False) print(untransformed_bbox) ``` -------------------------------- ### Create and Manipulate Path Objects with svgelements Source: https://context7.com/meerk40t/svgelements/llms.txt Illustrates the creation and manipulation of SVG path objects using the `svgelements` library. It shows how to parse paths from strings, construct paths from segment objects, build paths programmatically, combine paths and shapes, query path properties like bounding box and length, access subpaths, and convert coordinates. ```python from svgelements import * # Parse path from SVG path data string path = Path('M 100 100 L 300 100 L 200 300 z') # Create path from PathSegment objects path = Path( Move(100 + 100j), Line(100 + 100j, 300 + 100j), Line(300 + 100j, 200 + 300j), Close(200 + 300j, 100 + 100j) ) # Build paths programmatically with method chaining path = Path() path.move((0, 0), (0, 100), (100, 100), 100 + 0j) path.line((200, 200)) path.cubic((20, 33), (25, 25), (100, 100)) path.quad((50, 50), (100, 0)) path.closed() # Add close command # Path arithmetic - combine paths and shapes combined = Path("M10,10z") + Circle("12,12", 2) print(combined.d()) # Output: M 10,10 Z M 14,12 A 2,2 0 0,1 12,14 A 2,2 0 0,1 10,12 A 2,2 0 0,1 12,10 A 2,2 0 0,1 14,12 Z # Query path propertiesbox = path.bbox() # Bounding box (x_min, y_min, x_max, y_max) length = path.length() # Total path length point = path.point(0.5) # Point at 50% along path # Access subpaths path = Path('M 0,0 Q 50,50 100,0 M 20,20 v 20 h 20 v-20 h-20 z') subpath_count = path.count_subpaths() # Returns 2 subpath1 = path.subpath(1) print(subpath1.d()) # 'M 20,20 L 20,40 L 40,40 L 40,20 L 20,20 Z' # Reverse path direction path.reverse() # Convert to relative or absolute coordinates path_string = path.d(relative=False) # Absolute coordinates path_string = path.d(relative=True) # Relative coordinates ``` -------------------------------- ### Reverse Path and Subpaths Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates reversing the order of segments within a `Path` object using the `reverse()` method. This can be applied to the entire path or individual subpaths. ```python from svgelements import Path path = Path("M1,1 1,2 2,2 2,1z") * "scale(2)" path.reverse() print(path) multi_subpath = Path('M 0,0 Q 50,50 100,0 M 20,20 v 20 h 20 v-20 h-20 z') reversed_subpath = multi_subpath.subpath(1).reverse() print(reversed_subpath) ``` -------------------------------- ### CSS Length Unit Conversions Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates the functionality of the Length class for converting CSS length units like 'mm' to other units such as inches. It highlights the ability to specify a PPI for pixel-based conversions. ```python from svgelements import Length # Convert 25mm to inches mm_to_inches = Length('25mm').in_inches() print(mm_to_inches) # Output: 0.9842525 # Convert 100px to mm (assuming 96 PPI) px_to_mm = Length('100px').value(ppi=96) print(px_to_mm) # Output: 26.458333333333332 ``` -------------------------------- ### Handle Viewbox Transformations (Python) Source: https://context7.com/meerk40t/svgelements/llms.txt Explains how to parse SVG content with a viewBox attribute and how the library automatically applies scaling transformations. Also shows how to create Viewbox objects, obtain their equivalent transformation strings, and handle `preserveAspectRatio`. ```python from svgelements import * import io # Parse SVG with viewbox svg_content = ''' ''' # Viewbox automatically applies scaling transform svg = SVG.parse(io.StringIO(svg_content), reify=True) rect = list(svg.elements())[0] # Rectangle is automatically scaled by 5x due to viewbox # Create viewbox object from svgelements import Viewbox viewbox = Viewbox("0 0 100 100") viewbox.width = "500px" viewbox.height = "500px" # Get equivalent transformation transform = viewbox.transform() # Returns transform string # Handle preserveAspectRatio viewbox = Viewbox("0 0 200 100") viewbox.width = "400px" viewbox.height = "400px" viewbox.preserve_aspect_ratio = "xMidYMid meet" transform = viewbox.transform() # Scales uniformly and centers ``` -------------------------------- ### Parse SVG Files with svgelements Source: https://context7.com/meerk40t/svgelements/llms.txt Demonstrates how to parse SVG files using the `svgelements` library. It covers basic parsing, configuring parsing parameters like PPI and viewport dimensions, iterating through elements, and handling different SVG element types such as text, paths, shapes, and images. Optional dependencies like Pillow are noted for image loading. ```python from svgelements import * # Parse an SVG file svg = SVG.parse("example.svg") # Configure parsing with custom parameters svg = SVG.parse( "example.svg", reify=True, # Apply transform matrices ppi=96, # Pixels per inch width="8in", # Physical viewport width height="6in", # Physical viewport height color="black" # Current color for CSS ) # Iterate through all elements for element in svg.elements(): try: if element.values['visibility'] == 'hidden': continue except (KeyError, AttributeError): pass if isinstance(element, SVGText): print(f"Text element: {element}") elif isinstance(element, Path): if len(element) != 0: print(f"Path with {len(element)} segments") print(f"Bounding box: {element.bbox()}") print(f"Length: {element.length()}") elif isinstance(element, Shape): # Convert shape to path path = Path(element) path.reify() print(f"Shape converted to path: {path.d()}") elif isinstance(element, SVGImage): element.load() # Requires PIL/Pillow if element.image is not None: print(f"Image loaded: {element.image}") ``` -------------------------------- ### Work with Angles Source: https://context7.com/meerk40t/svgelements/llms.txt Illustrates creating Angle objects in degrees, radians, turns, and gradians, parsing them from CSS strings, and converting between these units. It shows how to use angles in transformations and with Point polar coordinates. ```python from svgelements import * # Create angles in different units angle = Angle.degrees(90) angle = Angle.radians(1.5707963267948966) angle = Angle.turns(0.25) angle = Angle.gradians(100) # Parse from CSS strings angle = Angle("90deg") angle = Angle("0.25turn") angle = Angle("1.5708rad") angle = Angle("100grad") # Convert between units degrees = angle.as_degrees radians = angle.as_radians turns = angle.as_turns grads = angle.as_gradians # Use in transformations matrix = Matrix.rotate(Angle.degrees(45)) rotated = Point(100, 0) * Matrix("rotate(0.5turn)") # Point(-100, 0) # Use with Point polar coordinates start = Point(0, 0) destination = start.polar_to(Angle.turns(0.125), 100) # Point at 45 degrees, 100 units away ``` -------------------------------- ### Represent and Apply Angles in Rotations Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates the use of the Angle class for defining rotations in various units (degrees, radians, turns, gradians) and applying them to Point objects. It also shows parsing CSS angle strings. ```python >>> Point(0,100) * "rotate(1turn)" Point(0,100) >>> Point(0,100) * "rotate(0.5turn)" Point(-0,-100) ``` -------------------------------- ### Parse and Manipulate Colors Source: https://context7.com/meerk40t/svgelements/llms.txt Demonstrates creating Color objects from various string and integer formats, accessing and modifying color components (red, green, blue, alpha), and obtaining the hex representation. It also shows how to calculate color distances and apply colors to shapes and paths. ```python from svgelements import * # Create colors from various formats color = Color('red') color = Color('#ff0000') color = Color('#f00') color = Color('rgb(255, 0, 0)') color = Color('rgb(100%, 0%, 0%)') color = Color('rgba(255, 0, 0, 0.5)') color = Color('hsl(120, 100%, 50%)') color = Color(0xFF0000) # Integer RGB value # Access color components red_value = color.red # 0-255 green_value = color.green # 0-255 blue_value = color.blue # 0-255 alpha_value = color.alpha # 0-255 # Modify color components color.red = 128 color.green = 64 color.blue = 32 color.alpha = 255 # Get hex representation hex_string = color.hex # '#804020' # Calculate color distances (Euclidean in RGB space) distance = Color.distance('red', 'blue') # 403.97524676643246 distance = Color('red').distance_to('blue') # Same result # Use with shapes and paths circle = Circle(stroke='yellow', fill='#ff0000') path = Path('M0,0 L100,100', stroke=Color('blue'), fill=Color('red')) ``` -------------------------------- ### SVG Dictionary Parsing with Transformations Source: https://github.com/meerk40t/svgelements/blob/master/README.md Demonstrates how to parse SVG path data from a dictionary, including applying a transform attribute. This snippet shows the combined effect of reading path data and a scale transformation. ```python >>> node = { 'd': "M0,0 100,0, 0,100 z", 'transform': "scale(0.5)"} >>> print(Path(node['d']) * Matrix(node['transform'])) M 0,0 L 50,0 L 0,50 Z ``` -------------------------------- ### SVG Shape Equality Source: https://github.com/meerk40t/svgelements/blob/master/README.md Illustrates the concept of shape equality in Svgelements, where different SVG shape objects (like Circle and Ellipse) or a Shape and a Path are considered equal if they decompose to the same Path data. ```python >>> Circle() == Ellipse() True >>> Rect() == Path('m0,0h1v1h-1z') True ``` -------------------------------- ### Subpath Manipulation Source: https://github.com/meerk40t/svgelements/blob/master/README.md Shows how to extract and manipulate subpaths within a larger Path object. Operations on a subpath are reflected in the original Path object. ```python from svgelements import Path p = Path('M 0,0 Q 50,50 100,0 M 20,20 v 20 h 20 v-20 h-20 z') print(p) q = p.subpath(1) q *= "scale(2)" print(p) q.reverse() print(p) ``` -------------------------------- ### Query Path Length Source: https://github.com/meerk40t/svgelements/blob/master/README.md Calculates the geometric length of path segments, including `QuadraticBezier` curves and transformed paths. The `length()` method is used for this purpose. ```python from svgelements import QuadraticBezier, Path bezier_length = QuadraticBezier("0,0", "50,50", "100,0").length() print(bezier_length) translated_path_length = (Path('M 0,0 Q 50,50 100,0') * "translate(40,40)").length() print(translated_path_length) ``` -------------------------------- ### Create and Manipulate SVG Shapes Source: https://context7.com/meerk40t/svgelements/llms.txt Shows how to create various SVG shapes like Rectangles, Circles, Ellipses, Lines, Polylines, and Polygons using different parameters. It also covers parsing shape data from dictionaries, converting shapes to path data, applying transformations, decomposing shapes into path data, checking shape equivalence, and combining shapes. ```python from svgelements import * # Create shapes from parameters rect = Rect(x=10, y=10, width=80, height=40) rect_rounded = Rect(10, 10, 80, 40, rx=5, ry=5) # Rounded corners circle = Circle(cx=50, cy=50, r=25) ellipse = Ellipse(cx=50, cy=50, rx=30, ry=20) line = SimpleLine(x1=0, y1=0, x2=100, y2=100) polyline = Polyline(0, 0, 100, 0, 100, 100, 0, 100) polygon = Polygon(0, 0, 100, 0, 100, 100, 0, 100) # Parse from dictionary (SVG attributes) rect = Rect({ 'x': "50", 'y': "51", 'width': "20", 'height': "10", 'rx': "4", 'ry': "2" }) # Convert shapes to path data path_data = circle.d() path_obj = Path(circle) # Transform shapes rotated_rect = rect * "rotate(45deg)" scaled_circle = circle * Matrix.scale(2) # Get shape path decomposition print(rect.d()) # Output: 'M 10,10 L 90,10 L 90,50 L 10,50 Z' # Shape equivalence (based on path decomposition) assert Circle(0, 0, 10) == Ellipse(0, 0, 10, 10) assert Rect(0, 0, 1, 1) == Path('M0,0 h1 v1 h-1 z') # Combine shapes combined = (Circle() + Rect()).bbox() # Returns bounding box of both total_length = (Circle() + Rect()).length() # Sum of perimeters ``` -------------------------------- ### SVG Point Representation and Operations Source: https://github.com/meerk40t/svgelements/blob/master/README.md Implements a Point class that functions similarly to Python's complex numbers, representing 2D coordinates. Supports methods for calculating distances, angles, polar coordinates, and reflections, and integrates with SVG path operations and matrix transformations. ```python from svgelements import Point, Angle, Length, Matrix # Example usage: print(Point(0+100j).distance_to([0,0])) # Polar to Point conversion print(Point(0).polar_to(Angle.turns(0.125), Length("5cm").value(ppi=96))) # Matrix transformation with Point and Angle print(Point(100,100) * Matrix("SkewX(0.05turn)")) ``` -------------------------------- ### In-place Transformation of SVG Paths Source: https://context7.com/meerk40t/svgelements/llms.txt Demonstrates how to apply transformations directly to an SVG Path object using a Matrix. The original path is modified in place. This is useful for applying scaling or rotation to existing path data. ```python from svgelements import Path, Matrix # Create a path object path = Path("M0,0 L100,100") # In-place scaling transformation path *= Matrix.scale(2) # Get absolute coordinates after transformation path_with_transform = Path("M0,0 L100,100") * Matrix.rotate(30) absolute_path = abs(path_with_transform) ``` -------------------------------- ### Convex Hull Computation Source: https://context7.com/meerk40t/svgelements/llms.txt Computes the convex hull for a list of points using the Point.convex_hull method. The result is a list of points lying on the convex hull in order. ```python points = [(3, 4), (4, 6), (18, -2), (9, 0)] hull = list(Point.convex_hull(points)) # Returns points on convex hull in order ``` -------------------------------- ### SVG Angle Representation and Conversion Source: https://github.com/meerk40t/svgelements/blob/master/README.md Represents CSS angle values ('deg', 'rad', 'grad', 'turn') using a float. Provides conversion capabilities between different angle units, such as degrees to radians. ```python from svgelements import Angle # Example usage: print(Angle.degrees(360).as_radians) ```