star algorithm in it’s infancy (aka – an algorithm for polygons)

To get a star, I’ll need to define 5 variables:

  1. x coordinate of center
  2. y coordinate of center
  3. a scalar “a” for the size of the interior pentagon
  4. a scale factor for the points “sfp” to determine what percent skinnier or squatter the points should be from perfect
  5. and a degree of rotation “r”

Let’s start with the first 3, which will define the interior pentagon without rotation.  Then I’ll make it a perfect star.  Then introduce rotation, and then pointiness.

algorithm in R

using conversion from polar to rectangular coordinates (x = a * cos(theta), y = a * sin(theta)), I can easily convert

cx <- 50
cy <- 50
a <- 20
theta <- 2 * pi / 5

z <- c(cx + a * cos(theta), cy + a * sin(theta),
cx + a * cos(2 * theta), cy + a * sin(2 * theta),
cx + a * cos(3 * theta), cy + a * sin(3 * theta),
cx + a * cos(4 * theta), cy + a * sin(4 * theta),
cx + a * cos(5 * theta), cy + a * sin(5 * theta)
)

round(z, 1)


var pentagon = document.createElementNS(“http://www.w3.org/2000/svg&#8221;, “polygon”);

pentagon.setAttribute(“points”, ” 56.2 69.0 33.8 61.8 33.8 38.2 56.2 31.0 70.0 50.0″); 
pentagon.setAttribute(“stroke”, “0”);
pentagon.setAttribute(“fill”, “white”);
mySvg.appendChild(pentagon);

But, I can do better than that for the calculation.  Here we go with a little loop:

cx <- 100
cy <- 150
a <- 30
sides <- 5

theta <- 2 * pi / sides

for(i in 1:sides){

if(i == 1){
z <- c(cx + a * cos(theta * i), cy + a * sin(theta * i ))
} else {
z <- c(z, c(cx + a * cos(theta * i), cy + a * sin(theta * i)))
}

}

round(z, 1)

and now introduce rotation…

oops!  The white was supposed to be rotated 1/8th of a circle.  Order of operations strikes again :).

Screenshot from 2013-07-22 18:21:06

There we go 🙂

Screenshot from 2013-07-22 18:26:09

(for the white one)
cx <- 100
cy <- 100
a <- 30
sides <- 5
rotate.factor <- 1/7

rotate <- 2 * pi * rotate.factor
theta <- 2 * pi / sides

for(i in 1:sides){

if(i == 1){
z <- c(cx + a * cos(theta * i + rotate), cy + a * sin(theta * i + rotate))
} else {
z <- c(z, c(cx + a * cos(theta * i + rotate), cy + a * sin(theta * i + rotate)))
}

}

And now, I just need the pointy bits.

Moreover, it’s time to let go of R and do these computations in javascript instead.  Goodbye beloved R 🙂

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s