star algorithm, built out & using javascript to define the SVG elements

step 1: defining the star/polygon algorithm in javascript instead of R, and introducing rotation starting point, color, the points of the stars, the scale of the points for the stars, and other fun.

I started off fairly hard-coded, but eventually got to a point where I could create a variable for each star with the required information along with a create star function & prototype.  I was especially excited that by essentially using polar coordinates to define the star points (angle and distance from center), I could have very consistent ways of defining where the points were.  This made it possible to be very general in the definition, allowing sides of many different lengths and either polygons or stars with a single algorithm.  In the loop, I convert the polar definitions (angle & distance) into x & y distances from the center.

From a javascript perspective, I discovered the “join” method which converted the strings for the points from an array.  I also used prototype in creating the function to create stars and started getting more comfortable with “this.” inside functions.  The push method for arrays and the math functions came in handy.

In terms of process, I started simple with things fairly hard-coded and then looked for places I could introduce loops or functions.

star parameters defined:

var star1 = { sides: 6, cx: 280,
cy: 130, a: 5, scaleFactorPercent:1,
rotateFactor:2 * Math.PI /20, color: “blue”, rotateSpeed: 150};

and the star function w/ star prototype for creating the star:

// function to create star
var starCoord = function(starDef){
this.starDef = starDef;

// and the prototype for the functions
starCoord.prototype.createStar = function(){
var rotate = this.starDef.rotateFactor;
var theta = 2 * Math.PI / this.starDef.sides;
var k = theta / 2
var z = [];
var toPoint = this.starDef.a * Math.cos(k) +
this.starDef.scaleFactorPercent * Math.sin(k) *
Math.tan(2 * k) * this.starDef.a;

// do the math to define distance from center
for(var i = 1; i <= this.starDef.sides; i++){
var angle = theta * i + rotate;
var x = + this.starDef.a * Math.cos(angle);
var y = + this.starDef.a * Math.sin(angle);
var xPoint = + toPoint * Math.cos(angle + k);
var yPoint = + toPoint * Math.sin(angle + k);

var pentagon = document.createElementNS(“;, “polygon”);
pentagon.setAttribute(“points”, z.join(” “));
pentagon.setAttribute(“stroke”, “0”);
pentagon.setAttribute(“fill”, this.starDef.color);


Leave a Reply

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

You are commenting using your 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