Reputation: 5008
I need some help writing an equation.
I want to generate hexagons of random sizes that are still "perfect"(proportional).
The leftmost vertex will be positioned at (0,0). I want to think of the other vertices in relation to that leftmost vertex. "So much up from the left vertex, so much right from it, so much down from it..." The reason this is not so straight forward, is because I need it to be proportional.
At the moment, this is what one of my statically defined hexagons look like:
// return {
// x1: (x+0), y1: (y+0),
// x2: (x+30), y2: (y-50),
// x3: (x+83), y3: (y-50),
// x4: (x+113), y4: y,
// x5: (x+83), y5: (y+50),
// x6: (x+30), y6: (y+50)
// };
I'm doing this in JavaScript, but the formula is really what I'm after. Thanks for your help.
Solution
Here is what my function ended up looking like BTW:
If you want to see what I was doing this is it: http://www.sidequestsapps.com/projects/CaptoType/game.html
function drawRotatingHexagon(leftX, middleY, radius, ctx) {
//console.log(x + ',' + y);
var centerX = (Math.floor(leftX)+radius); // Calculate center x coord
var centerY = middleY; // Calculate center y coord
ctx.translate(centerX, middleY); // Center pivot inside hexagon
ctx.rotate(rotValue*(Math.PI/180)); // Rotate
ctx.translate(-centerX, -middleY); // Un-Translate
for (var c=1; c<=3;c++) { // How many layers to draw
ctx.beginPath();
ctx.moveTo (centerX+radius*Math.cos(0), centerY+radius*Math.sin(0));
for (var i=1; i<=6;i++) {
ctx.lineTo(centerX+radius*Math.cos(i*Math.PI/3),
centerY+radius*Math.sin(i*Math.PI/3));
}
ctx.stroke();
}
};
Upvotes: 0
Views: 2077
Reputation: 105015
A hexagon is a regular polygon and has these properties:
Here's an example of a function that will draw a non-rotated hexagon with a specified radius and with its leftmost vertex at a specified point:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// draw your original hexagon
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(30,-50);
ctx.lineTo(83,-50);
ctx.lineTo(113,0);
ctx.lineTo(83,50);
ctx.lineTo(30,50);
ctx.closePath();
ctx.lineWidth=3;
ctx.stroke();
// same hexagon using drawHexagon()
ctx.strokeStyle='red';
ctx.lineWidth=1;
drawHexagon(0,0,113/2);
function drawHexagon(leftX,middleY,radius){
var centerX=leftX+radius;
var centerY=middleY;
ctx.beginPath();
ctx.moveTo (centerX+radius*Math.cos(0), centerY+radius*Math.sin(0));
for (var i=1; i<=6;i++) {
ctx.lineTo(centerX+radius*Math.cos(i*2*Math.PI/6), centerY+radius*Math.sin(i*2*Math.PI/6));
}
ctx.closePath();
ctx.stroke();
}
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<h4>Fn() to draw hexagon with specified radius and left-midpoint.</h4>
<canvas id="canvas" width=300 height=300></canvas>
Upvotes: 3
Reputation: 51835
then just scale the points
xi=Xi*scale;
yi=Yi*scale;
Upvotes: 0