About Generating Animated SVGs on the Fly

You can generate animated SVG images on the fly using the svgwrite library, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.http import HttpResponse
import svgwrite
from svgwrite.animate import AnimateMotion

def create_animated_svg(request):
    drawing = svgwrite.Drawing(
        size=("100%", "100%"), profile="tiny"
    )
    outer_circle = drawing.circle(
        center=("50%", "50%"), r="20%", fill="#215a00"
    )
    inner_circle = drawing.circle(
       center=("50%", "50%"), r="10%", fill="#fff"
    )
    drawing.add(outer_circle)
    drawing.add(inner_circle)
    # Animate the circles
    motion = AnimateMotion(
        path=(
            "M -25,0 "
            "a 25,25 0 1,1 50,0 "
            "a 25,25 0 1,1 -50,0"
        ),
        dur="1.5s",
        repeatCount="indefinite",
    )
    outer_circle.add(motion)
    inner_circle.add(motion)
    svg_data = drawing.tostring()
    return HttpResponse(svg_data, content_type="image/svg+xml")

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2 Python 3 SVG svgwrite