Contents

svgwrite animation code examples

0

svgwrite code example to create an animated SVG where we animate a circle by growing it’s size

Source Code

import svgwrite

def create_animated_svg():
    dwg = svgwrite.Drawing('animated_example.svg', profile='tiny')

    # Create a group for the animation
    animation_group = dwg.add(dwg.g(id='animation_group'))

    # Define the animated circle
    circle = dwg.circle(center=(100, 100), r=50, fill='red')


    # Define the animation grow parameters
    animation_params = {
        'attributeName': 'r',
        'from': '10',
        'to': '100',
        'dur': '3s',
        'repeatCount': 'indefinite'
    }

    # Create the animation element
    animationGrow = dwg.animate(**animation_params)

    # Add the animation to the circle
    circle.add(animationGrow)

    # Add the circle to the animation group
    animation_group.add(circle)

    # Add the animation group to the drawing
    dwg.add(animation_group)

    # Save the SVG file
    dwg.save()

if __name__ == '__main__':
    create_animated_svg()

In this example, we create an animated SVG that showcases a growing circle.

First, we import the svgwrite module and define a function called create_animated_svg(). Inside the function, we create an svgwrite.Drawing object, specifying the output file name (‘animated_example.svg’) and the profile (’tiny’).

We then create a group (svgwrite.g) called animation_group that will contain the animated elements.

Next, we define the circle using the svgwrite.circle function, setting its center coordinates, radius, and fill color.

We define the animation parameters using a dictionary, specifying the attribute to animate (attributeName), the initial value (from), the final value (to), the duration of the animation (dur), and the repeat count (repeatCount).

We create the animation element using the svgwrite.animate function, passing the animation parameters as keyword arguments.

We add the animation element to the circle using the add() method.

We add the circle to the animation group using the add() method.

Finally, we add the animation group to the drawing, and save the SVG file using the save() method.

Running this code will generate an SVG file called ‘animated_example.svg’ with an animated circle that grows from radius 10 to radius 100 over a 3-second duration, continuously repeating the animation.

Generated SVG Image

svg example

About svgwrite

svgwrite - A Python library to create SVG drawings.