### 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