Taco Steemers

A personal blog.
☼ / ☾

Programmatically creating scalable vector graphics (SVG)

This is a small note on programmatically creating scalable vector graphics . For this we use Python with svgwrite which was simply the first tool I found. We will not be comparing different tools.

When creating graphics for posters, programs, or the web there are some advantages in using scalable vector graphics over regular graphics such as PNG and JPG. SVG is scalable (resizeable) without any loss of detail, or 'fuzzyness'.

Here we see the output of the source code used in this example . You can zoom in as much as you like without the graphic looking 'pixelated'. This is becasue SVG does not use pixels to describe the graphic, it uses vectors . Note that the program that you use to look at the SVG file may limit how far you can zoom; the browser I used to proof-read my post only allows a 2x zoom. However, there are no technical limitations.

The basic idea is that we create an object with a shape and a location. Then we add that object to our 'canvas', the SVG document. Like so:

# Creating a canvas
svg_document = svgwrite.Drawing(filename = "using-svgwrite.svg", size = ("100px", "100px"))

# Creating a line 
lineA = svg_document.line((xStart, yStart), (xEnd, yEnd), stroke_width = 1, stroke = colorA)

# Placing the line on the canvas
svg_document.add(lineA)

It is that simple.

In the source code we use two different code paths for the 'horizontal' and the 'vertical' four-leaf clover. If the code had better structure, and the methods returned elements rather than adding them to the document immediately, we could have used the 'rotate' transformation to rotate the four-leaf clover as we wished.

One of the clovers doesn't look quite right. I was not able to get the 'swirl' to look right on all four leafs. Can you solve that?

You can create prettier patterns than the ones shown here, but I have deliberately not included mine. It is much more fun to try creating your own patterns than it is to look at someone else's!

Another library you might want to look at is Cairo, which has bindings for many different languages, according to Cairo's Wikipedia page .

The source was run with Python 2.7.3 and svgwrite 1.1.6.