How to draw a simple Pentagon in canvas

余生颓废 提交于 2019-12-10 06:37:57

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/36529781/how-to-draw-a-simple-pentagon-in-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!