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:
The PHP code
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 |
// Play around with these parameters: $pointCount = 5; $innerRadius = 25; $outerRadius = 50; // The magic: $piPart = (pi() / $pointCount); $starX = 50; $starY = 50; $points = array(); $piOffset = pi(); // We have to add an offset, otherwise our star is upside down ;-) // Generate the points by crunching some numbers: for($i = 0; $i < $pointCount * 2; $i+=2) { $points[] = ($starX + (sin($piOffset + $piPart * $i) * $outerRadius)) . ',' . ($starY + (cos($piOffset + $piPart * $i)) * $outerRadius); $points[] = ($starX + (sin($piOffset + $piPart * ($i + 1)) * $innerRadius)) . ',' . ($starY + (cos($piOffset + $piPart * ($i + 1))) * $innerRadius); } // Time to render some SVG: $svg = sprintf('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="300" height="300"> <polygon cx="%1$d" cy="%2$d" stroke="black" fill="none" points="%3$s"></polygon> </svg>', $starX, $starY, implode(' ', $points)); echo $svg; // It's that easy! |
So let’s breakdown what happens here:
- 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.
- 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 π.
- The $piOffset parameter is added as a static constant, because otherwise our star will be upside-down.
- 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.
- 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:
1 2 3 |
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="300" height="300"> <polygon cx="50" cy="50" stroke="black" fill="none" points="50,0 35.305368692688,29.774575140626 2.4471741852423,34.549150281253 26.223587092621,57.725424859374 20.610737385376,90.450849718747 50,75 79.389262614624,90.450849718747 73.776412907379,57.725424859374 97.552825814758,34.549150281253 64.694631307312,29.774575140626"></polygon> </svg> |
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?
★ ★ ★ ★ ★