Skip to content

Instantly share code, notes, and snippets.

@gavinsykes
Last active July 30, 2021 15:39
Show Gist options
  • Save gavinsykes/4d83d3af966e6bf8dc687c1beb3bf0fa to your computer and use it in GitHub Desktop.
Save gavinsykes/4d83d3af966e6bf8dc687c1beb3bf0fa to your computer and use it in GitHub Desktop.
Generating SVG path data for a star in JavaScript
const genStarPathData = (points,cx,cy,radius) => {
let radii = {
outer : radius, // this will be given to us when the function is called,
inner : radius * Math.cos(2 * Math.PI / points) / Math.cos(Math.PI /points)
/*
Wait, why Math.PI instead of 360 and 180? Well I remembered this time before
putting too much work in - JavaScript works in radians, not degrees!
π radians = 180° */
};
/* Now to redo the whole methodology as we can't really have an xpoints and
ypoints array, we don't know how many of each there will be! */
/* For each point we will have 2 coordinates, so let's create an array of
points, each with an x and y property: */
let pointsArray = [];
for (let i = 1; i <= points; i++) {
if (i == 1) {
pointsArray.push({
x: cx,
y: cy - radius
});
} else {
pointsArray.push({
x: cx + (radii.outer * Math.sin(2 * i * Math.PI / points)),
y: cy - (radii.outer * Math.cos(2 * i * Math.PI / points))
});
}
pointsArray.push({
x: cx + (radii.inner * Math.sin((2 * i + 1) * Math.PI / (2 * points))),
y: cy - (radii.inner * Math.cos((2 * i + 1) * Math.PI / (2 * points)))
});
};
let pathString = pointsArray
.slice(1)
.reduce(
(accumulator,current) => accumulator + `L${current.x} ${current.y} `,
`M${pointsArray[0].x} ${pointsArray[0].y} `
) + 'Z';
return pathString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment