drawsvg: Programmatic SVG and Animation

2.4.1 · active · verified Thu Apr 16

drawsvg is a Python 3 library designed for programmatically generating SVG (Scalable Vector Graphics) images and animations. It supports rendering drawings to various formats including PNG and MP4, and allows for interactive display within Jupyter Notebook and Jupyter Lab environments. The library maintains an active development status with regular updates, with version 2.4.1 being the latest stable release.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a simple SVG drawing with a circle, rectangle, and text. It then saves the output to an SVG file. Instructions for displaying in Jupyter Notebook and saving to PNG are also included, highlighting the optional dependencies for the latter.

import drawsvg as draw
import os

# Create a new drawing with a viewBox of 200x100, origin at center
d = draw.Drawing(200, 100, origin='center')

# Draw a red circle centered at (0,0)
d.append(draw.Circle(0, 0, 40, fill='red'))

# Draw a blue rectangle
d.append(draw.Rectangle(-90, -45, 60, 30, fill='blue', stroke='black', stroke_width=2))

# Draw some text
d.append(draw.Text('Hello drawsvg!', 20, 0, 30, center=True, fill='green'))

# Save the drawing to an SVG file
d.save_svg('example.svg')

# To display in a Jupyter Notebook, simply put 'd' as the last line in a cell:
# d

# To save as PNG (requires Cairo and 'drawsvg[all]' installation)
# if os.path.exists('/usr/bin/cairo-svg'): # Simple check for Cairo-SVG presence
#    d.save_png('example.png')
# else:
#    print("Cairo not installed, cannot save PNG. See 'install' section.")

print("Generated example.svg")

view raw JSON →