# javascript怎么画正五边形？

javascript怎么画正五边形？下面本篇文章给大家介绍一下。有一定的参考价值，有需要的朋友可以参考一下，希望对大家有所帮助。

Polygon.js —— 正多边形的类，在构造函数中求得所有的顶点，放在数组vertices

```var Point = function(x, y)
{
this.x = x;
this.y = y;
};

var Polygon = function(x, y, radius, sides)
{
this.x = x;
this.y = y;
this.sides = sides;
this.vertices = getPoints(x, y, radius, sides);

var points = [],
angle = 0,
centerAngle = 2 * Math.PI / sides;

for(var i = 0;  i < sides;  i++){
points.push(new Point( x + radius * Math.sin(angle), y - radius * Math.cos(angle) ));
angle += centerAngle;
}
console.log(points);
return points;
}

this.strokeStyle = 'black';
this.fillStyle = 'rgba(200, 200, 200, 1)';
};

Polygon.prototype = {

createPath: function(context){

context.beginPath();
context.moveTo(this.vertices[0].x, this.vertices[0].y);
for(var i = 1;  i < this.sides;  i++){
context.lineTo(this.vertices[i].x, this.vertices[i].y);
}
context.closePath();
},

stroke: function(context){

context.save();
this.createPath(context);
context.strokeStyle = this.strokeStyle;
context.stroke();
context.restore();
},

fill: function(context){

context.save();
this.createPath(context);
context.fillStyle = this.fillStyle;
context.fill();
context.restore();
}
}```

drawPolygon.js —— 把多边形画到canvas上

```function init(){

var canvas = document.getElementById('canvas'),
cxt = canvas.getContext('2d');

var polygon = new Polygon(200, 200, 130, 5);
polygon.stroke(cxt);
}```