user1103309
user1103309

Reputation:

How to create a polygon shape with flat sides in HTML5?

I'm using the following JS code to draw a 16-sided polygon:

context.beginPath();
var x_offset = 350;
var y_offset = 350;
var sides = 16;
var r = 300;
context.strokeStyle = "#000000";
for (i = 0; i < (sides); i++) {
    x = x_offset + (r * Math.cos(2 * Math.PI * i / sides));
    y = y_offset + (r * Math.sin(2 * Math.PI * i / sides));
    context.moveTo(x, y);
    x = x_offset + (r * Math.cos(2 * Math.PI * (i+1) / sides));
    y = y_offset + (r * Math.sin(2 * Math.PI * (i+1) / sides));
    context.lineTo(x, y);
}
context.stroke();

This is working fine, except that I want the polygon to have a 'flat' sides (top, bottom, left, right). In the picture below you see 2 polygons: the polygon with the red background color is what I want to achieve, the transparent polygon is the one generated by the code above.

Question: how can I generate a polygon with flat sides like the red one? Do I need to do a context.rotate()? I would prefer not too, to avoid all the translate() stuff.

polygons, example and mine

Upvotes: 2

Views: 729

Answers (1)

6502
6502

Reputation: 114599

You can just rotate by half of the stepping angle

context.beginPath();
for (var i = 0; i < sides; i++) {
    var angle = 2 * Math.PI * (i + 0.5) / sides;
    var x = x_offset + (r * Math.cos(angle));
    var y = y_offset + (r * Math.sin(angle));
    if (i == 0) context.moveTo(x, y);
           else context.lineTo(x, y);
}
context.closePath();

I made some minor changes like using local variables and factoring out the angle computation (the added 0.5 is what is needed to have a vertical side).

Note that the polygon will have also horizontal sides only if the number of sides is a multiple of 4.

Upvotes: 2

Related Questions