·

photo credit: kitsch via photopin (license)

Generate a SVG star in PHP

Tags: ,

Don’t ask my why, but today I had to draw a star with SVG. Being just math, this is easy to do with some basic sinus- and cosinus-calculations. So here’s how you can create this SVG graphic with PHP:

Screen Shot 2015-08-11 at 22.46.49

The PHP code

So let’s breakdown what happens here:

  1. In the first few lines I declare some parameters. Nothing special here. You can play around with those to see how they affect the star.
  2. The parameter $piPart  is a number that is added in each iteration when I’m calculating the star. A star is basically nothing more than a circle where the odd vectors in the sequence are of a further distance from the center then the even vectors. Hence the use of π.
  3. The $piOffset  parameter is added as a static constant, because otherwise our star will be upside-down.
  4. In the for -loop I am calculating each point of the star. Notice that the increment value is 2. This is needed because I want to add 2 vectors each time: one for the inner radius and one for the outer radius.
  5. And last but not least, create a simple <svg> -element that contains a <polygon> -element that has all the points of our stars.

Example output of the SVG-data:

It’s that easy! And note that even though this example is done in PHP, it’s calculations can easily be ported to any other language as well.

Update: A working example if this code can be seen at a little experiment I’m currently creating at http://boom.gielberkers.com/generator.php?item=star

Visitors give this article an average rating of 3.1 out of 5.

How would you rate this article?

Leave a Reply