Skip to content

Instantly share code, notes, and snippets.

@Breefield
Created August 12, 2012 04:12
Show Gist options
  • Save Breefield/3329668 to your computer and use it in GitHub Desktop.
Save Breefield/3329668 to your computer and use it in GitHub Desktop.
Drawing a Hexagon with Paper.js
// Create a Paper.js Path to draw a line into it:
var hexagon = new Path();
// Color our path black
hexagon.strokeColor = 'black';
// How many points do we want our object to have
var points = 6;
// How large should it be
var radius = 60;
// 0 to 2PI is a circle, so divide that by the number of points
// in our object and that's how many radians we should put a new
// point in order to draw the shape
var angle = ((2 * Math.PI) / points);
// For as many vertices in the shape, add a point
for(i = 0; i <= points; i++) {
// Add a new point to the object
hexagon.add(new Point(
// Radius * Math.cos(number of radians of the point) is the x position
radius * Math.cos(angle * i),
// And the same thing with Math.sin for the y position of the point
radius * Math.sin(angle * i)
));
}
// Offset the shape so it's fully displayed on the canvas
hexagon.position.x += 200;
hexagon.position.y += 200;
@marquizzo
Copy link

marquizzo commented Aug 1, 2016

This is very useful, thanks!

I recommend using var hexagon = new Path({closed: true});
And then for(i = 0; i < points; i++) {}

That way if you want to manipulate each segment in a polygon you only have points amount to manipulate, not points + 1.. For example, a pentagon should only have 5 points, not 6.

Additionally, polygons with strokes look better when the path is closed, leaving no gaps at the start point if you're setting your strokeCap to "butt".

@Govi-p
Copy link

Govi-p commented Dec 5, 2017

Hi,

I am drawing 6 hexagons(HoneyComb structure) In typescript onInit using the below mentioned method,
drawHexagon(positionX,positionY){
console.log('draw Hexagon');
var tool1 = new Tool();
this.hexagon = new Path();
for(let i = 0; i <= this.noOfDimension; i++) {

this.hexagon.add(new Point(
  this.radius * Math.cos(this.angle * i), 
  this.radius * Math.sin(this.angle * i)
));

}
this.hexagon.position.x += positionX; //300;
this.hexagon.position.y += positionY; //300;
}
=> In mouse click i wants to fill any color in hexagons. the color should fill in all hexagons.
=> I used the below code to fill color. But it is not working as expected. It fills color in only one Hexagon, even this also sometimes not working on mouse click.
this.hexagon.onClick = function(event){
this.fillColor = "pink";
}

Please Help to resolve the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment