You are here

Drawing regular polygons in javascript canvas

Geometric shapes such as regular polygons are useful building blocks for drawing more complex elements within JavaScript canvas tags. The following block shows 3, 4, 5, 6, 7, 8, 9 and 10 sided regular polygons.
Drawing regular polygons can be done by choosing the position for the center of the polygon, moving to the perimeter and then drawing a series of lines using the Math.cos(), Math.sin() and Math.PI functions. In JavaScript, angles are measured in radians. There are 2*PI radians in a circle. The number of points to plot around the circle is 2*PI divided by the number of sides on the desired polygon. The following code snippet will draw a hexagon:
  1. // hexagon
  2. var numberOfSides = 6,
  3.     size = 20,
  4.     Xcenter = 25,
  5.     Ycenter = 25;
  6.  
  7. cxt.beginPath();
  8. cxt.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          
  9.  
  10. for (var i = 1; i <= numberOfSides;i += 1) {
  11.     cxt.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
  12. }
  13.  
  14. cxt.strokeStyle = "#000000";
  15. cxt.lineWidth = 1;
  16. cxt.stroke();
  17.  

By changing the value of numberOfSides, any regular polygon can be drawn. Altering the value of size allows larger and smaller shapes to be drawn.

You might also like:

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.

Filtered HTML

  • The Lexicon module will automatically mark terms that have been defined in the lexicon vocabulary with links to their descriptions. If there are certain phrases or sections of text that should be excluded from lexicon marking and linking, use the special markup, [no-lexicon] ... [/no-lexicon]. Additionally, these HTML elements will not be scanned: a, abbr, acronym, code, pre.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd><p><br /><img>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions. It IS case sensitive
Image CAPTCHA
Enter the characters shown in the image.