正多边形的编程绘制(javascript) | 玄数

2017-12-28

如何用程序来绘制正多边形?

正多边形

如图,正五边形ABCDE关于y轴对称,B与E,C与D互为对称点。A的坐标为(0, r)。 半径OA旋转一个内角θ,便是OB,此时B的坐标为(r·sin0, r·cos0)。继续旋转,可以得到OC、OD、OE等半径,坐标求法与OB的一致,只需把对应的角度依次增加(2π/边数)。

 

编程的流程图如下:

 

algorithm regular polygon

使用两个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.radius = radius;
    this.sides = sides;
    this.vertices = getPoints(x, y, radius, sides);    

    function 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);
}

正多边形的绘制(javascript)