Skip to content

Instantly share code, notes, and snippets.

@sbrl
Last active January 30, 2018 22:59
Show Gist options
  • Save sbrl/2edcdcd0bfd583febb02 to your computer and use it in GitHub Desktop.
Save sbrl/2edcdcd0bfd583febb02 to your computer and use it in GitHub Desktop.
Shape.js: A regular shape drawing class. #es6 #module #microlibrary
/*******************************************************************************
******************************* ES6 Shape Class *******************************
*******************************************************************************
* v0.1
*******************************************************************************
* A class that draws regular shapes of a given size with an arbitrary number of
* sides. Also supports rotation and translation (even after the shape has been
* created).
*
*
*
* This class was originally written on Codepen. Links:
*
* Codepen: https://codepen.io/sbrl/details/EPQbQo/
* Blog post: (coming soon!)
*
* This class depends on the vector class that I wrote earlier. Link:
*
* https://gist.github.com/sbrl/69a8fa588865cacef9c0
*
* Bug reports can be made as a comment on this gist, or
* sent to <[email protected]>. Alternatively, you can tweet
* me at @SBRLabs.
*******************************************************************************
* Author: Starbeamrainbowlabs <[email protected]>
*
* Changelog:
* v0.1: Initial revision.
*
*/
class Shape
{
constructor(pos, sides, radius, rotation)
{
this.position = pos;
this.rotation = (typeof rotation == "number") ? rotation : 0;
this.radius = radius;
this.sides = sides;
this.points = [];
this.recalculatePoints();
}
get firstPoint()
{
return this.points[0];
}
get lastPoint()
{
return this.points[this.points.length - 1];
}
// From http://stackoverflow.com/a/7198179/1460422
recalculatePoints()
{
this.points = [];
for(let n = 0; n < this.sides; n++)
{
this.points.push(new Vector(
this.radius * Math.cos(Math.PI*2 * (n / this.sides) + this.rotation - Math.PI/2) + this.position.x,
this.radius * Math.sin(Math.PI*2 * (n / this.sides) + this.rotation - Math.PI/2) + this.position.y
));
}
}
rotate(rotation, absolute)
{
if(!absolute)
this.rotation += rotation;
else
this.rotation = rotation;
this.recalculatePoints();
}
translate(vector, absolute)
{
if(!absolute)
this.position.add(vector);
else
this.position = vector;
this.recalculatePoints();
}
lines(context, sidelimit)
{
for(let i = 0; i < this.points.length; i++)
{
context.lineTo(this.points[i].x, this.points[i].y);
if(typeof sidelimit == "number" && i >= sidelimit - 1)
return;
}
context.lineTo(this.points[0].x, this.points[0].y)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment