Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a simple Pentagon in canvas

Tags:

I want to create a Pentagon, I succeeded in creating such pentagon.

But my pentagon is not right, because it doesn't stand right on the surface.

How can I fix it? I need an elegant answer not just a quick fix.

Update:

I would like to know also another thing :

How can I draw a Pentagon using coordinates only, I mean the 5 coordinates of the pentagon?

I want to draw a pentagon based on five known cordinates(v1,v2..v5) and without any loop,to draw some kind of path between five points.

$(function(){
var canvas=document.getElementById("canvas");
var cxt=canvas.getContext("2d");
    // hexagon
    var numberOfSides = 5,
        size = 100,
        Xcenter = 150,
        Ycenter = 150;

    cxt.beginPath();
    cxt.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          

    for (var i = 1; i <= numberOfSides;i += 1) {
      cxt.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
    }

    cxt.strokeStyle = "#000000";
    cxt.lineWidth = 1;
    cxt.stroke();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=650 height=500></canvas>
like image 667
Brk Avatar asked Apr 10 '16 12:04

Brk


1 Answers

Interesting question, you can shift the sin/cos values so the bottom line aligns horizontally:

$(function(){
   var canvas=document.getElementById("canvas");
   var cxt=canvas.getContext("2d");
    // hexagon
    var numberOfSides = 5,
        size = 100,
        Xcenter = 150,
        Ycenter = 150,
        step  = 2 * Math.PI / numberOfSides,//Precalculate step value
        shift = (Math.PI / 180.0) * -18;//Quick fix ;)

    cxt.beginPath();
    //cxt.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          

    for (var i = 0; i <= numberOfSides;i++) {
    	var curStep = i * step + shift;
        cxt.lineTo (Xcenter + size * Math.cos(curStep), Ycenter + size * Math.sin(curStep));
    }

    cxt.strokeStyle = "#000000";
    cxt.lineWidth = 1;
    cxt.stroke();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=650 height=500></canvas>
like image 132
Mohsen Avatar answered Oct 22 '22 02:10

Mohsen