SVG: Spiky Star

Let’s say we would like to create spiky star. One option would be to utilize tag path. Picture below should help to explain, how to design path. In the center “C” is a unit circle with radius 1. Each spike has base 0.8 wide (2*0.4) and height 1.5. Now let’s compute absolute coordinates for the green path points. Vertical distance for the first point g1 has value sqrt(1*1 -0.4*0.4) = 0.9165… Here is list of the few points.

g1[-0.4,-0.9165], g2[0,-2.4165], g3[0.4,-0.9165], g4[0.9165,-0.4], g5[2.4165,0], ...
C g1 g2 g3 g4 r1 r2 r3 r4

In similar fashion can be computed red path points. It is obvious, that in this case is much easier to compute their coordinates. On the other hand radius of the arc connecting point r3 and r4 is not just 1, but it has a value sqrt(1*1+ 0.4*0.4) = 1.077… In reality arc with radius 1 or arc with radius 1.077 is almost the same, especially for narrow spike base.

r1[-0.4,-1], r2[0,-2.5], r3[0.4,-1], r4[1,-0.4], r5[2.5,0], ...

Here is a star with 4 spikes with base spike 0.4 (2*.2) and height 3 using absolute coordinates:

<svg viewBox="-5 -5 10 10" width="600" height="600" >
<defs>
  <g id="Spiky4StarAbsolute">
     <path d="M-0.2,-1
	L 0,-4 0.2,-1	 A1,1 0,0,1    1,-0.2
	L 4,0    1,0.2   A1,1 0,0,1  0.2,1
	L 0,4 -0.2,1     A1,1 0,0,1   -1,0.2
	L-4,0   -1,-0.2  A1,1 0,0,1 -0.2,-1
	z" fill="lightblue" stroke="blue" stroke-width="0.03"
      />
 </g>
</defs>
 <use xlink:href="#Spiky4StarAbsolute" ></use>
</svg>

And here is a star with 4 spikes with base spike 0.4 (2*.2) and height 3 using absolute coordinates:

<svg viewBox="-4 -4 8 8" width="600" height="600" >
<defs>
  <g id="Spiky4StarRelative">
     <path d="M-0.2,-1
	l .2,-3   .2,3	  a1,1 0,0,1  0.8, 0.8
	l  3,.2   -3,0.2  a1,1 0,0,1 -0.8, 0.8
	l-.2,3  -0.2,-3   a1,1 0,0,1 -0.8,-0.8
	l -3,-.2   3,-0.2 a1,1 0,0,1  0.8,-0.8
	 z"  fill="pink" stroke="red" stroke-width="0.03"/>
  </g>
</defs>
 <use xlink:href="#Spiky4StarRelative" ></use>
</svg>

Here is PHP code, which can generate spiky star svg image.

....
<svg viewBox="-4 -4 8 8" width="600" height="600" >
<defs>
  <g id="Spiky4StarRelative">
<?php
  $fill = "lightgray";
  $stroke = "silver";
  $strokeWidth = 0.03;
  $r = 1.0;
  $w = 0.2;
  $d = $r - $w;
  $h = 2.2;
  echo <<<END
     <path d="M-$w,-$r
        l $w,-$h  $w,$h   a$r,$r 0,0,$r  $d, $d
        l  $h,$w  -$h,$w  a$r,$r 0,0,$r -$d, $d
        l-$w,$h  -$w,-$h   a$r,$r 0,0,$r -$d,-$d
        l -$h,-$w   $h,-$w a$r,$r 0,0,$r  $d,-$d
         z"  fill="$fill" stroke="$stroke" stroke-width="$strokeWidth"/>

END
?>
  </g>
</defs>
 <use xlink:href="#Spiky4StarRelative" ></use>
</svg>
....
This entry was posted in workday and tagged . Bookmark the permalink.

Leave a Reply