svgwrite Documentation

repository·master·Indexed 20 days ago

https://github.com/mozman/svgwrite

svgwrite is a pure Python library used to programmatically create SVG drawings. It is a lightweight tool with no external dependencies, providing support for core SVG attributes, conditional processing, document and graphical event attributes, and detailed configuration for SVG animations including timing, interpolation modes, and value sequences.

Tokens
29.8K
Snippets
77
Records
155
Agent score
69%

What's inside svgwrite

  1. How SVG elements and mixins are organized

    master

    svgwrite categorizes SVG components into several functional groups:

    • Structural Elements: Containers like Drawing, SVG, Group, Defs, Symbol, Marker, Use, and Hyperlink.
    • Graphical Elements: Shapes such as Line, Rect, Circle, Ellipse, Polyline, Polygon, and Path.
    • Text Objects: Text, TSpan, TRef, TextPath, and TextArea.
    • Paint Servers: LinearGradient and RadialGradient.
    • Masking: Mask and ClipPath.
    • Animation: Set, Animate, AnimateColor, AnimateMotion, and AnimateTransform.
    • Filter Effects: Filter.

    Additionally, Mixins provide shared functionality across elements, including ViewBox, Transform, XLink, Presentation, MediaGroup, Markers, and Clipping.

  2. Use conditional processing attributes in SVG

    master

    Conditional processing attributes are used to control whether or not an SVG element is processed by the renderer. While most SVG elements support these, they are not universal.

    According to the W3C specification, common conditional processing attributes include:

    • requiredExtensions: Specifies required extensions for the element to be processed.
    • requiredFeatures: Specifies required features for the element to be processed.
    • systemLanguage: Specifies the language of the element's content.
  3. Use the feTile filter primitive to create tiled patterns

    master

    The feTile filter primitive is used to fill a target rectangle with a repeated, tiled pattern of an input image.

    To create a repeating pattern, you typically define an input image with a smaller filter primitive subregion (using x, y, width, and height) than the feTile element itself. The feTile element then replicates this reference tile in both X and Y directions to fill its own target rectangle.

    Key Concepts:

    • Target Rectangle: Defined by the x, y, width, and height attributes on the feTile element.
    • Tile Placement: The top-left corner of each tile is located at (x + i * width, y + j * height), where i and j are integers.
    • Artifact Warning: When using transformations like shear or rotation, be aware that interpolation can cause edge artifacts (unexpected opacity changes) at the boundaries where tiles meet.
  4. Use graphical event attributes for user interaction

    master

    Graphical event attributes allow you to specify scripts to run in response to specific user interaction events within an SVG. These attributes are used to embed event handlers directly into SVG elements.

    Supported event attributes include:

    • onactivate: Triggered when an element is activated.
    • onclick: Triggered when an element is clicked.
    • onfocusin: Triggered when an element receives focus.
    • onfocusout: Triggered when an element loses focus.
    • onload: Triggered when an element is loaded.
    • onmousedown: Triggered when a mouse button is pressed down on an element.
    • onmousemove: Triggered when the mouse moves over an element.
    • onmouseover: Triggered when the mouse moves onto an element.
    • onmouseout: Triggered when the mouse moves off an element.
    • onmouseup: Triggered when a mouse button is released on an element.
  5. Use the feConvolveMatrix filter element

    master

    The feConvolveMatrix element applies a matrix convolution filter effect to an input image. This process combines pixels in the input image with neighboring pixels to achieve various imaging operations such as blurring, edge detection, sharpening, embossing, and beveling.

    To use this filter, you must define a kernelMatrix and specify the dimensions of the matrix using order.

    # Note: Actual Python implementation usage would involve calling the feConvolveMatrix class/method
    # provided by the svgwrite library to generate the <feConvolveMatrix> SVG element.
  6. Use the feMorphology filter element to fatten or thin artwork

    master

    The feMorphology filter primitive is used to perform "fattening" (dilation) or "thinning" (erosion) of artwork. It is most commonly used to manipulate the alpha channel of an image.

    How it works

    • Dilation (fattening): The output pixel is the component-wise maximum of the R, G, B, and A values within the kernel rectangle.
    • Erosion (thinning): The output pixel is the component-wise minimum of the R, G, B, and A values within the kernel rectangle.

    Key Behaviors

    • Alpha Channel: Because it operates on premultiplied color values, the resulting color values will always be less than or equal to the alpha channel.
    • Infinite Extent: If the input is constant and has infinite extent, the operation has no effect. If it is a tile, the filter uses periodic boundary conditions.
    • Zero Radius: Setting the radius to zero disables the effect, resulting in a transparent black image.
  7. Use the feDisplacementMap filter element

    master

    The feDisplacementMap filter primitive uses pixel values from a second input image (in2) to spatially displace the pixels of a primary input image (in).

    Key behaviors:

    • Displacement Scale: The scale attribute determines the maximum range of displacement in either the x or y direction. A value of 0 results in no effect.
    • Channel Selection: You can specify which color channels from the in2 image are used to drive the x and y displacement via xChannelSelector and yChannelSelector.
    • Interpolation: Because displacement often results in source pixel locations falling between existing pixels, high-quality rendering typically requires bilinear or bicubic interpolation.
  8. How SVG filter primitives operate

    master

    Filter primitives in svgwrite operate on premultiplied RGBA samples. Most raster effect filtering operations take 1 to N input RGBA images and produce a single output RGBA image. The resulting color and opacity values are clamped to allowable ranges (e.g., negative values are adjusted to zero).

    Color Spaces

    Color space behavior is controlled by two properties:

    • color-interpolation-filters: Determines the color space for filtering operations. Initial value is linearRGB.
    • color-interpolation: Determines the color space for other color operations. Initial value is sRGB.

    To ensure consistency (for example, when coordinating gradients with filtering), you may need to explicitly set these properties to match.

  9. Use feSpecularLighting to create specular highlights

    master

    The feSpecularLighting filter primitive simulates specular reflections (shininess) by using the alpha channel of a source graphic as a bump map. The resulting image is an RGBA image based on the light color and follows the Phong lighting model.

    Key usage patterns:

    • Combining with textures: Because feSpecularLighting produces a non-opaque image (where the alpha channel is the max of the color components), it is intended to be combined with a texture using the add operator of the feComposite method.
    • Simulating multiple lights: You can simulate multiple light sources by adding several specular light maps together before applying the result to the texture image.
    • Pairing with diffuse lighting: It is common to use feSpecularLighting alongside feDiffuseLighting to achieve a complete lighting effect.
  10. Use the feDiffuseLighting filter element

    master

    The feDiffuseLighting filter primitive creates a lighting effect by using the alpha channel of an input image as a bump map. The resulting image is an RGBA opaque image based on the light color with an alpha of 1.0. The lighting calculation follows the standard diffuse component of the Phong lighting model.

    To simulate complex lighting, you can:

    1. Combine the produced light map with a texture image using the multiply compositing method of feComposite.
    2. Simulate multiple light sources by adding several light maps together before applying them to the texture image.
  11. Create a Mask in svgwrite

    master

    A Mask is used to define transparency and visibility for elements. Unlike a ClipPath, a mask can use different coordinate systems for its attributes and its content.

    Key attributes for Mask include:

    • maskUnits: Defines the coordinate system for x, y, width, and height. Default is 'objectBoundingBox'.
    • maskContentUnits: Defines the coordinate system for the contents of the mask. Default is 'userSpaceOnUse'.
    • x, y, width, height: Define the rectangle for the largest possible offscreen buffer. Defaults are x='-10%', y='-10%', width='120%', and height='120%'.