-1

I need to draw a Pentagon with html 5 canvas in Javascript. Not much else to write here. I have tried looking it up, but a lot of the examples don't work correctly.

Mitch Mitchell
  • 735
  • 1
  • 7
  • 5
  • 1
    Possible duplicate of [How to draw polygons on an HTML5 canvas?](https://stackoverflow.com/questions/4839993/how-to-draw-polygons-on-an-html5-canvas). A pentagon is like any other polygon. You can use javascript to figure out the math of the coordinates. – Sunny Patel Jul 31 '17 at 17:28
  • I am aware that a pentagon is just like any other polygon, I have issues with math, geometry in particular. – Mitch Mitchell Jul 31 '17 at 17:42
  • Then you should try asking in [Math StackExchange](https://math.stackexchange.com/), as you clarified that you don't have a programming issue. – Sunny Patel Jul 31 '17 at 17:47
  • Also, I did some more Googling for you. I found that answer was ripped of this [blog article](http://www.arungudelli.com/html5/html5-canvas-polygon/). Have fun. – Sunny Patel Jul 31 '17 at 17:53
  • A pentagon is one type of "regular polygon". This post in Docs shows how to draw [regular polygons](https://stackoverflow.com/documentation/html5-canvas/5493/polygons/18145/regular-polygon#t=201707311803114820515). – markE Jul 31 '17 at 18:04

1 Answers1

0

The pentagon starts at the 3oclock pos use rotation to change the start position in radians. ie To start at the top rotation is -90deg = -Math.PI / 2

function pentagon(x, y, radius, rotation){
    for(var i = 0; i < 5; i ++){
        const ang = (i / 5) * Math.PI * 2 + rotation;
        ctx.lineTo(
            Math.cos(ang) * radius + x,
            Math.sin(ang) * radius + y
        );
     }
     ctx.closePath();
}

ctx.beginPath();
pentagon(100,100,50,-Math.PI / 2);
ctx.fill();
ctx.stroke();
Shaido
  • 27,497
  • 23
  • 70
  • 73
Blindman67
  • 51,134
  • 11
  • 73
  • 136