### Setting and Getting SVG Attributes Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/base.md Illustrates the dictionary-like interface for setting and getting SVG attributes on a BaseElement. It also shows how to update multiple attributes at once using the `update` method, with examples of attribute name transformations. ```default element['attribute'] = value value = element['attribute'] attribs = { 'class': 'css-class', 'stroke': 'black', } element.update(attribs) ``` -------------------------------- ### from Attribute Source: https://github.com/mozman/svgwrite/blob/master/doc/attributes/animation_value.md Specifies the starting value for an animation. ```APIDOC ## from ### Description Specifies the starting value of the animation. ### Method Attribute ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **from** (value) - Required - The starting value for the animation. ### Request Example ``` from = "10" ``` ### Response #### Success Response (200) N/A (This is an attribute definition) #### Response Example N/A ``` -------------------------------- ### Install svgwrite from source (Shell) Source: https://github.com/mozman/svgwrite/blob/master/README.rst This command installs svgwrite by building it from its source code. This method is useful if you have downloaded the source distribution or need to install a specific version not available via pip. Requires Python and setuptools to be installed. ```shell python setup.py install ``` -------------------------------- ### Create and Use Patterns with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt This section demonstrates how to define and utilize SVG patterns for tiling graphics with the svgwrite library. It includes examples of creating dot, checkerboard, and stripe patterns, and applying them as fills to shapes. Transformations can also be applied to patterns, as shown with a rotated stripe pattern. ```python import svgwrite dwg = svgwrite.Drawing('patterns.svg', size=('400px', '300px')) # Create a simple pattern pattern = dwg.pattern( insert=(0, 0), size=(20, 20), id='dots', patternUnits='userSpaceOnUse' ) pattern.add(dwg.circle(center=(10, 10), r=5, fill='blue')) dwg.defs.add(pattern) # Checkerboard pattern checker = dwg.pattern(size=(20, 20), id='checker', patternUnits='userSpaceOnUse') checker.add(dwg.rect((0, 0), (10, 10), fill='black')) checker.add(dwg.rect((10, 10), (10, 10), fill='black')) checker.add(dwg.rect((10, 0), (10, 10), fill='white')) checker.add(dwg.rect((0, 10), (10, 10), fill='white')) dwg.defs.add(checker) # Stripe pattern stripes = dwg.pattern(size=(10, 10), id='stripes', patternUnits='userSpaceOnUse') stripes.add(dwg.rect((0, 0), (5, 10), fill='red')) stripes.add(dwg.rect((5, 0), (5, 10), fill='white')) dwg.defs.add(stripes) # Use patterns dwg.add(dwg.rect((10, 10), (120, 80), fill=pattern.get_paint_server())) dwg.add(dwg.rect((140, 10), (120, 80), fill=checker.get_paint_server())) dwg.add(dwg.rect((270, 10), (120, 80), fill=stripes.get_paint_server())) # Pattern with transformation rotated_stripes = dwg.pattern(size=(14, 14), id='diagonal', patternUnits='userSpaceOnUse') rotated_stripes.add(dwg.rect((0, 0), (7, 14), fill='green')) rotated_stripes.add(dwg.rect((7, 0), (7, 14), fill='lightgreen')) rotated_stripes.rotate(45) dwg.defs.add(rotated_stripes) dwg.add(dwg.circle((70, 200), 50, fill=rotated_stripes.get_paint_server())) dwg.save() ``` -------------------------------- ### Attribute Handling Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/base.md Demonstrates how to set and get SVG attributes using dictionary-like access and the update method. ```APIDOC ## Attribute Handling ### Description This section illustrates how to interact with SVG attributes of a BaseElement instance. ### Usage Set/get SVG attributes: ```python element['attribute'] = value value = element['attribute'] attribs = { 'class': 'css-class', 'stroke': 'black', } element.update(attribs) ``` **Rules for keys in `update()`:** 1. Trailing ‘_’ will be removed (`'class_'` -> `'class'`). 2. Inner ‘_’ will be replaced by ‘-’ (`'stroke_width'` -> `'stroke-width'`). **Rules for keyword arguments in `__init__()`:** 1. Add trailing ‘_’ to reserved keywords: `'class_'`, `'from_'`. 2. Replace inner ‘-’ by ‘_’: `'stroke_width'`. ``` -------------------------------- ### SVG Animations with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Shows how to implement SMIL animations in SVG using the svgwrite library. Examples include animating attributes like 'width' and 'fill', and using 'set' animations for discrete changes. ```python import svgwrite dwg = svgwrite.Drawing('animations.svg', size=('400px', '300px')) # Simple attribute animation rect = dwg.rect((10, 10), (50, 50), fill='blue') anim = dwg.animate( attributeName='width', values=[50, 100, 50], dur='2s', repeatCount='indefinite' ) rect.add(anim) dwg.add(rect) # Color animation circle = dwg.circle((150, 50), 30, fill='red') color_anim = dwg.animate( attributeName='fill', values=['red', 'green', 'blue', 'red'], dur='3s', repeatCount='indefinite' ) circle.add(color_anim) dwg.add(circle) # Set animation (discrete value change) rect2 = dwg.rect((220, 10), (50, 50), fill='orange') set_anim = dwg.set(attributeName='fill', to='purple', begin='1s', dur='1s') set_anim.set_target('fill') set_anim.set_timing(begin='click', dur='2s') rect2.add(set_anim) dwg.add(rect2) ``` -------------------------------- ### Install svgwrite using pip (Shell) Source: https://github.com/mozman/svgwrite/blob/master/README.rst This command installs the svgwrite package using pip, the standard package installer for Python. Ensure pip is installed and up-to-date before running this command. ```shell pip install svgwrite ``` -------------------------------- ### Get Paint Server IRI for Gradient in Python Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/gradients.md Shows how to retrieve the functional IRI (Internal Resource Identifier) for a gradient using the `get_paint_server` method. This IRI is used to reference the gradient in SVG elements. ```python import svgwrite draw = svgwrite.Drawing() # Create a gradient (e.g., radial) radial_gradient = draw.radial_gradient() radial_gradient.add_stop_color(offset='0%', color='green') # Get the paint server IRI for the gradient paint_server_iri = radial_gradient.get_paint_server() print(f"Paint Server IRI: {paint_server_iri}") # Example of using the IRI to fill a shape rect = draw.rect(insert=(0, 0), size=(100, 100), fill=paint_server_iri) draw.add(rect) print(draw.tostring()) ``` -------------------------------- ### SolidColor Class Initialization Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/solidcolor.md Constructor for creating a SolidColor paint server element. ```APIDOC ## CLASS SolidColor ### Description The SolidColor element is a paint server that provides a single color with opacity. It can be referenced like other paint servers such as gradients. ### Method __init__(color='currentColor', opacity=None, **extra) ### Parameters #### Initialization Parameters - **color** (string) - Optional - The solid color to be used. Defaults to 'currentColor'. - **opacity** (float) - Optional - The opacity of the solid color in the range 0.0 to 1.0. - **extra** (dict) - Optional - Additional SVG attributes. ### SVG Attributes - **solid-color** (string) - Specifies the color. Supports 'currentColor', standard color values, or 'inherit'. - **solid-opacity** (float) - Specifies the opacity value. Values outside 0.0-1.0 are clamped. ### Request Example ```python from svgwrite.solidcolor import SolidColor # Create a solid color element color_server = SolidColor(color='red', opacity=0.5) ``` ### Response #### Success Response - **instance** (SolidColor) - Returns a configured SolidColor object ready to be added to an SVG definition section. ``` -------------------------------- ### Create and Apply SVG Markers using svgwrite Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/marker.md Demonstrates how to instantiate a Marker object, add graphical content to it, register it in the drawing's defs section, and apply it to a polyline using set_markers or direct attribute assignment. ```python dwg = svgwrite.Drawing() # create a new marker object marker = dwg.marker(insert=(5,5), size=(10,10)) # red point as marker marker.add(dwg.circle((5, 5), r=5, fill='red')) # add marker to defs section of the drawing dwg.defs.add(marker) # create a new line object line = dwg.add(dwg.polyline( [(10, 10), (50, 20), (70, 50), (100, 30)], stroke='black', fill='none')) # set marker (start, mid and end markers are the same) line.set_markers(marker) # or set markers direct as SVG Attributes 'marker-start', 'marker-mid', # 'marker-end' or 'marker' if all markers are the same. line['marker'] = marker.get_funciri() # NEW in v1.1.11 # set individually markers, to just set the end marker set other markers to None or False: line.set_markers((None, False, marker)) ``` -------------------------------- ### BaseElement Initialization and Attribute Update Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/base.md Demonstrates how to initialize a BaseElement and update its attributes, including handling attribute name transformations (e.g., 'stroke_width' to 'stroke-width'). This is a workaround for older versions of the library that had an 'attribs' parameter. ```default # replace element = BaseElement(attribs=adict) #by element = BaseElement() element.update(adict) ``` -------------------------------- ### Line Shape API Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/shapes.md Defines a line segment starting at one point and ending at another. ```APIDOC ## POST /svgwrite/shapes/Line ### Description The line element defines a line segment that starts at one point and ends at another. ### Method POST ### Endpoint /svgwrite/shapes/Line ### Parameters #### Request Body - **start** (2-tuple) - Required - Start point (x1, y1) - **end** (2-tuple) - Required - End point (x2, y2) - **extra** (dict) - Optional - Additional SVG attributes ### Request Example { "start": [0, 0], "end": [100, 100] } ### Response #### Success Response (200) - **status** (string) - Success message #### Response Example { "status": "Line object created" } ``` -------------------------------- ### TRef Element Initialization and Href Setting Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/text.md Demonstrates how to initialize a TRef element, which references other text elements, and how to set the href attribute to specify the referenced element's ID or object. ```python from svgwrite.text import TRef # Create a TRef referencing an element by its ID string tref_by_id = TRef('my_text_element_id') # Assuming 'referenced_element' is a BaseElement object with an 'id' attribute # from svgwrite.base import BaseElement # referenced_element = BaseElement(id='another_element') # tref_by_object = TRef(referenced_element) # Set the href attribute for an existing TRef object tref_instance = TRef('initial_id') tref_instance.set_href('new_target_id') # or # tref_instance.set_href(another_BaseElement_object) ``` -------------------------------- ### Create SVG Line Element Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/drawing.md Factory method to create an SVG Line element. It takes start and end coordinates and accepts additional keyword arguments for SVG attributes. ```python drawing.line(start=(0, 0), end=(0, 0), **extra) ``` -------------------------------- ### keySplines Attribute Source: https://github.com/mozman/svgwrite/blob/master/doc/attributes/animation_value.md Defines cubic Bézier control points for animation pacing when calcMode is 'spline'. ```APIDOC ## keySplines ### Description A set of Bézier control points associated with the **keyTimes** list, defining a cubic Bézier function that controls interval pacing. The attribute value is a semicolon-separated list of control point descriptions. Each control point description is a set of four values: x1 y1 x2 y2, describing the Bézier control points for one time segment. The values must all be in the range 0 to 1. ### Method Attribute ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **keySplines** (list) - Required - A semicolon-separated list of Bézier control point sets (x1 y1 x2 y2). ### Request Example ``` keySplines = "0.42 0 0.58 1; 0.42 0 0.58 1" ``` ### Response #### Success Response (200) N/A (This is an attribute definition) #### Response Example N/A ``` -------------------------------- ### Create SVG elements using factory methods in Python Source: https://github.com/mozman/svgwrite/blob/master/doc/overview.md Demonstrates how to initialize a drawing, create a hyperlink, and add a rectangle element using the factory methods provided by the Drawing class. ```python dwg = svgwrite.Drawing() link = dwg.add(dwg.a("http://link.to/internet")) square = link.add(dwg.rect((0, 0), (1, 1), fill='blue')) ``` -------------------------------- ### Filter Class Initialization Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/filters.md Initializes a Filter element, which acts as a container for filter primitives and a factory for creating them. Parameters define the filter effects region's start point, size, and resolution. It can also inherit properties from other filters. ```python svgwrite.filters.Filter(start=(x, y), size=(width, height), resolution='x-pixels y-pixels', inherit='xlink:href') ``` -------------------------------- ### Define Radial Gradient with Center and Radius in Python Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/gradients.md Demonstrates how to initialize a RadialGradient object in Python, specifying the center point and radius. This is useful for creating radial color transitions in SVG. ```python import svgwrite draw = svgwrite.Drawing() # Define a radial gradient with center at (50, 50) and radius 40 radial_gradient = draw.radial_gradient(center=(50, 50), r=40) # Add stop colors to the gradient radial_gradient.add_stop_color(offset='0%', color='blue', opacity=0.5) radial_gradient.add_stop_color(offset='100%', color='red', opacity=1) # Add the gradient to the drawing draw.add(radial_gradient) print(draw.tostring()) ``` -------------------------------- ### POST /svgwrite/text/TextPath Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/text.md Initializes a TextPath element to render text along the shape of a specified path. ```APIDOC ## POST /svgwrite/text/TextPath ### Description Creates a new TextPath element that references a path and renders text along its shape. ### Method POST ### Endpoint svgwrite.text.TextPath(path, text, startOffset=None, method='align', spacing='exact', **extra) ### Parameters #### Request Body - **path** (string/object) - Required - ID string or Path object to follow. - **text** (string) - Required - The text content to render. - **startOffset** (number) - Optional - Offset from the beginning of the path. - **method** (string) - Optional - 'align' or 'stretch'. - **spacing** (string) - Optional - 'exact' or 'auto'. ### Request Example { "path": "path_id_1", "text": "Hello World", "method": "align" } ### Response #### Success Response (200) - **element** (object) - The created TextPath SVG element. ``` -------------------------------- ### Creating feDiffuseLighting Filter Primitive Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/filters.md Creates and adds an feDiffuseLighting filter primitive. This primitive simulates diffuse lighting on the input image, creating a matte appearance. It requires an input image and can optionally define its region. ```python filter_element.feDiffuseLighting(in_='input_image', start=(x, y), size=(width, height)) ``` -------------------------------- ### Generate Basic Shapes SVG using svgwrite Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/shapes.md Demonstrates the creation of various basic SVG shapes (lines, circle, rectangle, ellipse) using the svgwrite library in Python. It shows how to add elements to a drawing, set attributes directly or via helper functions, and manage groups with specific styles. ```python import svgwrite from svgwrite import cm, mm def basic_shapes(name): dwg = svgwrite.Drawing(filename=name, debug=True) hlines = dwg.add(dwg.g(id='hlines', stroke='green')) for y in range(20): hlines.add(dwg.line(start=(2*cm, (2+y)*cm), end=(18*cm, (2+y)*cm))) vlines = dwg.add(dwg.g(id='vline', stroke='blue')) for x in range(17): vlines.add(dwg.line(start=((2+x)*cm, 2*cm), end=((2+x)*cm, 21*cm))) shapes = dwg.add(dwg.g(id='shapes', fill='red')) # set presentation attributes at object creation as SVG-Attributes circle = dwg.circle(center=(15*cm, 8*cm), r='2.5cm', stroke='blue', stroke_width=3) circle['class'] = 'class1 class2' shapes.add(circle) # override the 'fill' attribute of the parent group 'shapes' shapes.add(dwg.rect(insert=(5*cm, 5*cm), size=(45*mm, 45*mm), fill='blue', stroke='red', stroke_width=3)) # or set presentation attributes by helper functions of the Presentation-Mixin ellipse = shapes.add(dwg.ellipse(center=(10*cm, 15*cm), r=('5cm', '10mm'))) ellipse.fill('green', opacity=0.5).stroke('black', width=5).dasharray([20, 20]) dwg.save() if __name__ == '__main__': basic_shapes('basic_shapes.svg') ``` -------------------------------- ### Setting Animation Values - Python Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/animate.md The set_value method configures animation attributes such as values, calcMode, keyTimes, keySplines, from, to, and by. This allows for precise control over how an attribute changes over time. ```python from svgwrite.animate import Animate animate = Animate() animate.set_value(values=['0', '100'], calcMode='linear', keyTimes=['0', '1'], from_='0', to='100') ``` -------------------------------- ### Draw Arc Paths with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Demonstrates how to create a path element and use the push_arc method to draw curved segments. It includes parameters for target coordinates, rotation, radius, and sweep direction. ```python arc_path = dwg.path(fill='none', stroke='purple', stroke_width=3) arc_path.push('M', 50, 300) arc_path.push_arc( target=(150, 300), rotation=0, r=50, large_arc=True, angle_dir='+', absolute=True ) dwg.add(arc_path) ``` -------------------------------- ### Drawing Initialization and Attributes Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/drawing.md This section details the initialization of the Drawing object and how to set/get its SVG attributes and other properties like filename and defs. ```APIDOC ## Drawing Initialization and Attributes ### Description Initializes an SVG drawing object, which represents the top-level SVG element. It can contain various SVG elements and provides methods for managing the drawing's content and file operations. Attributes can be set and retrieved using dictionary-like access. ### Method `__init__` ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `__init__`: - **filename** (string) - Optional - Filesystem filename valid for `open()` - **size** (2-tuple) - Optional - Tuple representing (width, height), defaults to ('100%', '100%') - **extra** (keywords) - Optional - Additional SVG attributes for the SVG object, including: - **profile** (string) - Optional - Defines the SVG baseProfile ('tiny' or 'full') - **debug** (bool) - Optional - Switches validation on/off ### Attributes: - **filename** (string) - The filesystem filename associated with the drawing. - **defs** (Defs object) - The SVG defs section for defining reusable elements. ### Usage Examples: ```python # Setting and getting SVG attributes element['attribute'] = value value = element['attribute'] # Adding elements to the defs section drawing.defs.add(element) ``` ### Response #### Success Response (200) N/A (Constructor does not return a response in the typical API sense) #### Response Example N/A ``` -------------------------------- ### Creating feSpecularLighting Filter Primitive Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/filters.md Creates and adds an feSpecularLighting filter primitive. This primitive simulates specular lighting on the input image, creating highlights. It requires an input image and can optionally define its region. ```python filter_element.feSpecularLighting(in_='input_image', start=(x, y), size=(width, height)) ``` -------------------------------- ### Create feSpotLight Source Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/fe_diffuse_lighting.md Creates and adds a spot light source to the feDiffuseLighting filter. It requires source and target 3D points and accepts extra parameters. ```python feDiffuseLighting.feSpotLight(source=(0, 0, 0), target=(0, 0, 0), **extra) ``` -------------------------------- ### Add Style element to SVG drawing Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/style.md Demonstrates how to instantiate a style element and add it to the definitions section of an SVG drawing object using the svgwrite library. ```python drawing.defs.add(drawing.style('stylesheet-content')) ``` -------------------------------- ### Create SVG Path Elements with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Shows how to construct complex SVG paths using the svgwrite library in Python. It covers using the `path()` factory method and the `push()` method to add path commands like move, line, cubic bezier, and quadratic bezier curves, including closing paths and smooth curve commands. ```python import svgwrite dwg = svgwrite.Drawing('paths.svg', size=('400px', '400px')) # Basic path with move and line commands path = dwg.path(d='M 10,10') # Initial move command path.push('L 100,10') # Line to path.push('L 100,100') path.push('L 10,100') path.push('Z') # Close path path['fill'] = 'lightblue' path['stroke'] = 'navy' dwg.add(path) # Path with curves - push multiple commands at once curved_path = dwg.path(fill='none', stroke='red', stroke_width=2) curved_path.push('M', 150, 50) # Move to (150, 50) curved_path.push('C', 200, 0, 250, 100, 300, 50) # Cubic bezier curved_path.push('S', 350, 100, 350, 50) # Smooth cubic bezier dwg.add(curved_path) # Quadratic bezier curves quad_path = dwg.path(fill='none', stroke='green', stroke_width=2) quad_path.push('M', 10, 200) quad_path.push('Q', 60, 150, 110, 200) # Quadratic bezier quad_path.push('T', 210, 200) # Smooth quadratic bezier dwg.add(quad_path) ``` -------------------------------- ### Use Units and Helper Functions in SVG with Python Source: https://context7.com/mozman/svgwrite/llms.txt Illustrates the use of unit objects (cm, mm, px, inch, etc.) and utility functions like rgb and rect_top_left_corner for coordinate handling in svgwrite. This simplifies creating SVGs with precise measurements and complex positioning. Requires the svgwrite library. ```python import svgwrite from svgwrite import cm, mm, px, inch, pt, pc, em, ex, percent, deg, rad from svgwrite.utils import rgb, rect_top_left_corner dwg = svgwrite.Drawing('units.svg', size=(20*cm, 15*cm)) # Using unit multipliers rect1 = dwg.rect(insert=(1*cm, 1*cm), size=(5*cm, 3*cm), fill='lightblue') dwg.add(rect1) rect2 = dwg.rect(insert=(10*mm, 50*mm), size=(50*mm, 30*mm), fill='lightgreen') dwg.add(rect2) # Unit functions for multiple values line = dwg.line(start=cm(1, 8), end=cm(6, 8), stroke='black') # cm(x, y) -> '1cm,8cm' dwg.add(line) # RGB color helper color1 = rgb(255, 128, 0) # 'rgb(255,128,0)' color2 = rgb(100, 50, 75, '%') # 'rgb(100%,50%,75%)' circle = dwg.circle(center=(8*cm, 3*cm), r=2*cm, fill=color1) dwg.add(circle) # Calculate top-left corner from different insertion points # For centered insertion: center_point = (10*cm, 10*cm) size = (4*cm, 2*cm) top_left = rect_top_left_corner(center_point, size, pos='middle-center') dwg.add(dwg.rect(insert=top_left, size=size, fill='coral')) # Mark the center point dwg.add(dwg.circle(center=center_point, r=3, fill='black')) # Bottom-right insertion bottom_right = (15*cm, 12*cm) top_left2 = rect_top_left_corner(bottom_right, (3*cm, 2*cm), pos='bottom-right') dwg.add(dwg.rect(insert=top_left2, size=(3*cm, 2*cm), fill='khaki')) dwg.save() ``` -------------------------------- ### POST /svgwrite/text/TextArea Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/text.md Initializes a TextArea element for SVG 1.2 Tiny, allowing for text wrapping within a rectangular region. ```APIDOC ## POST /svgwrite/text/TextArea ### Description Creates a TextArea element for simple text wrapping within a defined region (SVG 1.2 Tiny profile). ### Method POST ### Endpoint svgwrite.text.TextArea(text=None, insert=None, size=None, **extra) ### Parameters #### Request Body - **text** (string) - Optional - Initial text content. - **insert** (tuple) - Optional - Insertion point coordinates. - **size** (tuple) - Optional - Dimensions of the text area. ### Request Example { "insert": [0, 0], "size": [100, 50] } ### Response #### Success Response (200) - **element** (object) - The created TextArea SVG element. ``` -------------------------------- ### Manage Groups, Symbols, and Hyperlinks Source: https://context7.com/mozman/svgwrite/llms.txt Illustrates how to organize SVG elements into groups for shared attributes, define reusable symbols, and wrap elements in hyperlinks. ```python group = dwg.g(id='my_group', stroke='blue', stroke_width=2, fill='none') group.add(dwg.rect(insert=(10, 10), size=(80, 60))) dwg.add(group) symbol = dwg.symbol(id='star_symbol') symbol.add(dwg.polygon(points=[(25, 0), (31, 19), (50, 19), (35, 31), (41, 50), (25, 38), (9, 50), (15, 31), (0, 19), (19, 19)])) dwg.defs.add(symbol) dwg.add(dwg.use(symbol, insert=(100, 150), size=(30, 30), fill='gold')) link = dwg.a(href='https://example.com', target='_blank') link.add(dwg.text('Click me!', insert=(10, 250), fill='blue')) dwg.add(link) ``` -------------------------------- ### Set SVG Presentation Attributes with Python Source: https://context7.com/mozman/svgwrite/llms.txt Demonstrates how to set fill, stroke, and dash properties for SVG elements using the Presentation mixin in svgwrite. It covers setting colors, opacity, stroke width, dash arrays, and using chained method calls or direct attribute assignment. No external dependencies are required beyond the svgwrite library. ```python import svgwrite dwg = svgwrite.Drawing('presentation.svg', size=('400px', '300px')) # Fill properties rect1 = dwg.rect((10, 10), (80, 50)) rect1.fill(color='blue', opacity=0.5, rule='evenodd') dwg.add(rect1) # Stroke properties rect2 = dwg.rect((100, 10), (80, 50), fill='none') rect2.stroke( color='red', width=3, opacity=0.8, linecap='round', # butt, round, square linejoin='round', # miter, round, bevel miterlimit=4 ) dwg.add(rect2) # Dash array line1 = dwg.line((10, 100), (190, 100)) line1.stroke('black', width=2) line1.dasharray([10, 5]) # 10px dash, 5px gap dwg.add(line1) line2 = dwg.line((10, 120), (190, 120)) line2.stroke('green', width=2) line2.dasharray([15, 5, 5, 5], offset=5) # Complex pattern with offset dwg.add(line2) # Chained method calls circle = dwg.circle((250, 50), 40) circle.fill('yellow', opacity=0.7).stroke('orange', width=4).dasharray([8, 4]) dwg.add(circle) # Direct attribute assignment rect3 = dwg.rect((200, 100), (100, 60)) rect3['fill'] = 'purple' rect3['fill-opacity'] = 0.6 rect3['stroke'] = 'darkviolet' rect3['stroke-width'] = 2 rect3['stroke-dasharray'] = '5,3,1,3' dwg.add(rect3) dwg.save() ``` -------------------------------- ### Styling SVG with CSS and Fonts using svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Demonstrates how to embed CSS stylesheets, apply CSS classes to SVG elements, reference external stylesheets, embed local fonts, and use web fonts within an SVG document using the svgwrite library. It also shows how to apply inline styles. ```python import svgwrite dwg = svgwrite.Drawing('styled.svg', size=('400px', '300px')) # Embed CSS stylesheet css = """ .highlight { fill: yellow; stroke: orange; stroke-width: 2; } .title { font-size: 24px; font-weight: bold; fill: navy; } .body { font-family: Georgia, serif; fill: #333; } rect:hover { fill: red; } """ dwg.embed_stylesheet(css) # Use CSS classes rect = dwg.rect((10, 10), (100, 50)) rect['class'] = 'highlight' dwg.add(rect) text = dwg.text('Styled Title', insert=(10, 100)) text['class'] = 'title' dwg.add(text) # External stylesheet reference dwg.add_stylesheet( href='styles.css', title='Main Stylesheet', alternate='no', media='screen' ) # Embed local font dwg.embed_font('CustomFont', 'fonts/MyFont.ttf') # Embed Google web font # dwg.embed_google_web_font('Roboto', 'https://fonts.googleapis.com/css?family=Roboto') # Use embedded font text_custom = dwg.text('Custom Font Text', insert=(10, 150)) text_custom['style'] = 'font-family: CustomFont; font-size: 20px;' dwg.add(text_custom) # Inline styles via style attribute rect2 = dwg.rect((10, 180), (150, 40)) rect2['style'] = 'fill: #ccc; stroke: #666; stroke-width: 1; opacity: 0.8;' dwg.add(rect2) dwg.save() ``` -------------------------------- ### Create and Save SVG Drawing with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Demonstrates how to create an SVG drawing using the svgwrite library in Python. It covers initializing a Drawing object, setting size and profile, adding basic shapes, and saving the drawing to a file in different formats (compact, pretty-printed). ```python import svgwrite from svgwrite import cm, mm, px, inch # Create a basic drawing with default size (100%, 100%) dwg = svgwrite.Drawing('output.svg') # Create drawing with specific size and SVG profile dwg = svgwrite.Drawing( filename='output.svg', size=('200mm', '100mm'), profile='full', # 'full' for SVG 1.1, 'tiny' for SVG 1.2 Tiny debug=True # Enable attribute validation ) # Set viewBox for user coordinate system dwg.viewbox(width=800, height=600) # Add elements to the drawing dwg.add(dwg.rect(insert=(10, 10), size=(100, 50), fill='blue')) dwg.add(dwg.circle(center=(150, 50), r=30, stroke='red', fill='none')) # Save to file dwg.save() # Save with pretty-printed XML dwg.save(pretty=True, indent=2) # Save to a different filename dwg.saveas('different_name.svg', pretty=True) # Get XML string representation xml_string = dwg.tostring() ``` -------------------------------- ### SVG Markers with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Illustrates the creation and application of custom markers (like arrowheads and dots) to SVG shapes such as lines, polylines, and paths using the svgwrite library. It demonstrates defining marker styles and applying them to different parts of a shape. ```python import svgwrite dwg = svgwrite.Drawing('markers.svg', size=('400px', '200px')) # Arrow marker for line ends arrow = dwg.marker( insert=(5, 5), size=(10, 10), orient='auto', id='arrow' ) arrow.add(dwg.path(d='M 0,0 L 10,5 L 0,10 z', fill='black')) dwg.defs.add(arrow) # Circle marker for vertices dot = dwg.marker(insert=(5, 5), size=(10, 10), id='dot') dot.add(dwg.circle((5, 5), 4, fill='red')) dwg.defs.add(dot) # Square marker square = dwg.marker(insert=(4, 4), size=(8, 8), id='square') square.add(dwg.rect((0, 0), (8, 8), fill='blue')) dwg.defs.add(square) # Apply markers to a line line = dwg.line((50, 50), (200, 50), stroke='black', stroke_width=2) line.set_markers((dot, None, arrow)) # (start, mid, end) dwg.add(line) # Apply markers to a polyline polyline = dwg.polyline( [(50, 100), (100, 150), (150, 100), (200, 150)], stroke='green', stroke_width=2, fill='none' ) polyline.set_markers((square, dot, arrow)) dwg.add(polyline) # Single marker for all positions path = dwg.path(d='M 250,50 Q 300,100 350,50 T 400,50', stroke='purple', fill='none') path.set_markers(dot) # Same marker for all dwg.add(path) dwg.save() ``` -------------------------------- ### SVG Clipping and Masking with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Illustrates how to use clipping paths and masks to control the visibility of SVG elements. This includes defining simple and complex clip paths, applying them to shapes and groups, and creating masks using gradients. ```python import svgwrite dwg = svgwrite.Drawing('clipping.svg', size=('400px', '300px')) # Define a clip path clip = dwg.clipPath(id='circle_clip') clip.add(dwg.circle(center=(100, 100), r=50)) dwg.defs.add(clip) # Apply clip path to an image or shape rect = dwg.rect(insert=(50, 50), size=(100, 100), fill='blue') rect['clip-path'] = 'url(#circle_clip)' dwg.add(rect) # Complex clip path with multiple shapes complex_clip = dwg.clipPath(id='complex_clip') complex_clip.add(dwg.rect((0, 0), (50, 100))) complex_clip.add(dwg.circle((75, 50), 30)) dwg.defs.add(complex_clip) group = dwg.g() group.add(dwg.rect((200, 20), (150, 100), fill='red')) group.add(dwg.rect((200, 20), (150, 100), fill='url(#pattern)', opacity=0.5)) group['clip-path'] = 'url(#complex_clip)' group.translate(0, 0) dwg.add(group) # Define a mask (uses alpha/luminance for transparency) mask = dwg.mask(id='fade_mask', start=(0, 0), size=(200, 100)) gradient = dwg.linearGradient(id='mask_grad') gradient.add_stop_color(0, 'white') # Fully visible gradient.add_stop_color(1, 'black') # Fully hidden dwg.defs.add(gradient) mask.add(dwg.rect((0, 0), (200, 100), fill=gradient.get_paint_server())) dwg.defs.add(mask) # Apply mask masked_rect = dwg.rect((20, 180), (200, 80), fill='purple') masked_rect['mask'] = 'url(#fade_mask)' dwg.add(masked_rect) dwg.save() ``` -------------------------------- ### SVG Path Animation with svgwrite Source: https://context7.com/mozman/svgwrite/llms.txt Demonstrates how to animate an SVG element along a defined path using svgwrite. This includes setting the path, duration, and repeat count for the animation, as well as rotating the element to follow the path direction. ```python import svgwrite dwg = svgwrite.Drawing('animation.svg', size=('400px', '300px')) # Motion along a path motion_path = 'M 50,150 C 100,100 200,200 300,150' moving_circle = dwg.circle((0, 0), 10, fill='green') motion = dwg.animateMotion( path=motion_path, dur='4s', repeatCount='indefinite' ) motion['rotate'] = 'auto' # Rotate along path direction moving_circle.add(motion) dwg.add(moving_circle) # Draw the motion path for reference dwg.add(dwg.path(d=motion_path, stroke='gray', fill='none', stroke_dasharray='5,5')) # Transform animation (rotation) spinning_rect = dwg.rect((0, 0), (40, 20), fill='cyan') spinning_rect.translate(300, 100) transform_anim = dwg.animateTransform( 'rotate', attributeName='transform', type='rotate', from_='0 20 10', to='360 20 10', dur='2s', repeatCount='indefinite' ) spinning_rect.add(transform_anim) dwg.add(spinning_rect) # Animation with timing control pulsing = dwg.circle((100, 250), 20, fill='magenta') pulse = dwg.animate(attributeName='r', values=[20, 30, 20]) pulse.set_timing(dur='1s', repeatCount='indefinite', begin='0s') pulse.freeze() # Keep final state when animation ends pulsing.add(pulse) dwg.add(pulsing) dwg.save() ``` -------------------------------- ### Drawing Use Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/drawing.md Creates an svgwrite.container.Use object for referencing and instantiating elements. ```APIDOC ## POST /drawing/use ### Description Creates an `svgwrite.container.Use` object. This element is used to reference and instantiate existing SVG elements, such as symbols or groups, at a specified location and size. ### Method POST ### Endpoint /drawing/use ### Parameters #### Query Parameters - **href** (string) - Required - The reference URL (e.g., '#my-symbol') to the element to be used. - **insert** (object) - Optional - Insertion point [x, y] for the referenced element. - **size** (array) - Optional - The size [width, height] to render the referenced element. ### Request Example ```json { "href": "#my-icon", "insert": [50, 50], "size": [20, 20] } ``` ### Response #### Success Response (200) - **element_id** (string) - The unique identifier for the created Use element. #### Response Example ```json { "element_id": "use-151" } ``` ``` -------------------------------- ### Create feMerge filter and add nodes in Python Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/fe_merge.md Demonstrates how to initialize an feMerge filter primitive and add multiple feMergeNode subelements using the svgwrite library. The layernames parameter accepts a list of strings corresponding to the input sources to be merged. ```python # Example of creating an feMerge filter merge = filter.feMerge(["SourceGraphic", "blur_result"]) # Adding additional nodes merge.feMergeNode(["shadow_result"]) ``` -------------------------------- ### Create fePointLight Source Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/fe_diffuse_lighting.md Creates and adds a point light source to the feDiffuseLighting filter. It requires a source 3D point (x, y, z) and accepts extra parameters. ```python feDiffuseLighting.fePointLight(source=(0, 0, 0), **extra) ``` -------------------------------- ### Create SVG Filter with Animated Point Light using svgwrite Source: https://github.com/mozman/svgwrite/blob/master/doc/classes/filters.md Demonstrates how to create an SVG filter with diffuse lighting and an animated point light source using the svgwrite Python library. It defines a filter, adds diffuse lighting, and then animates the x, y, and z coordinates of a point light. ```python import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import svgwrite dwg = svgwrite.Drawing("fePointLight.svg") filtr = dwg.defs.add( dwg.filter(id="DL", start=(0, 0), size=(500, 500), filterUnits="userSpaceOnUse")) diffuse_lighting = filtr.feDiffuseLighting( start=(0, 0), size=(500, 500), surfaceScale=10, diffuseConstant=1, kernelUnitLength=1, lighting_color="#f8f") point_light = diffuse_lighting.fePointLight( (500, 250, 250) ) point_light.add( dwg.animate('x', values=(0,100,500,100,0), dur='30s', repeatDur='indefinite')) point_light.add( dwg.animate('y', values=(0,500,400,-100,0), dur='31s', repeatDur='indefinite')) point_light.add( dwg.animate('z', values=(0,1000,500,-100,0), dur='37s', repeatDur='indefinite')) dwg.save() ``` -------------------------------- ### by Attribute Source: https://github.com/mozman/svgwrite/blob/master/doc/attributes/animation_value.md Specifies a relative offset value for an animation. ```APIDOC ## by ### Description Specifies a relative offset value for the animation. ### Method Attribute ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **by** (value) - Required - The relative offset value for the animation. ### Request Example ``` by = "50" ``` ### Response #### Success Response (200) N/A (This is an attribute definition) #### Response Example N/A ``` -------------------------------- ### Apply Geometric Transformations Source: https://context7.com/mozman/svgwrite/llms.txt Demonstrates the use of the Transform mixin to translate, rotate, and scale SVG elements, including rotation around specific center points. ```python rect1 = dwg.rect(insert=(10, 10), size=(50, 30), fill='red') rect1.translate(100, 0) dwg.add(rect1) rect2 = dwg.rect(insert=(10, 10), size=(50, 30), fill='green') rect2.rotate(45) dwg.add(rect2) rect3 = dwg.rect(insert=(200, 100), size=(50, 30), fill='blue') rect3.rotate(30, center=(225, 115)) dwg.add(rect3) rect4 = dwg.rect(insert=(10, 150), size=(50, 30), fill='purple') rect4.scale(2, 1.5) dwg.add(rect4) ```