Convert SVG path data to SVG polygon data

convert-svg-eye-catch
I am now engaging in creating some SVG data. I have some difficulty about conversion of SVG data structure. What I mean in this article is conversion from SVG path data to SVG polygon data. If you have some difficulty on this conversion, this article may help you.

Overview

There is some key functions to deal this matter, such as “getPointAtLength” in javascript or the same name function in Java apache batik SVG took kit. Indeed, I wanted to implement using python because I am using python to implement other programs in my project, but python and python SVG library do not have similar functions. My goal is to create a batch program which converts SVG path data to SVG polygon data, so I choose Java.

I placed the source on the github and you can use it as you like.

Conversion Flow

This is the conversion flow. So simple.

  1. Load SVG data (path data)
  2. Parse path data
  3. Sample some points on the path
  4. Create the polygon data using points sampled in 3rd step
  5. Write SVG data (polygon data)

More detail of this algorithm is showed here.

Part1. Load SVG data (Path data)

To load SVG data to your program, you can use SVGDocument class. One thing you should mind is that you have to boot the SVG Dom if you want more useful information about SVG such as path length et al. (See this link & this link)

Part2. Parse path data

If you load SVG data like I mentioned above, parsing path data and analysis (e.g. calculate total length) has finished. So just use the analyzed data to sample points on the path.

Part3. Sample some points on the path

This part is the core of conversion. To create the polygon, you have to define the points of polygon. In this conversion, the points of polygon have to be come form sampling some point on the path data. In my code, the number of “separate_points” is the number of sampling points, and “getPointAtLength” function tells you the coordinates of each sampled point.

Part4. Create the polygon data

First I tried to use SVGGraphics2D descrived in this article, but finally I didn’t use it because the function drawPolygon which help drawing polygon on SVG is only support for integer coordinates. My SVG path data contains float values, so I sought the way to draw polygon with float coordinates. The fastest and easiest way to achieve this is writing raw SVG polygon data to the output file using XML utilities.

Part5. Write SVG (polygon data)

The final step of this process is output SVG data to the file. This step is the same as way you write a ordinary XML file.

Appendix. Number of sampling points

Of course you can change number of sampling points. In this program, number of sampling points is given as one of argument. (“separate_points” is the number of sampling points in source code Part3) The more sampling points, the more precise the polygon shape, as below.

convert-svg-result-comparison