×

用js代替CSS,尝试画个5边形状

作者:andy0012020.04.29来源:Web前端之家浏览:7457评论:0
关键词:js多边形

用js代替CSS,尝试画个5边形状,来玩玩吧。

在一般情况下,会使用 x = radius * Math.cos(angle), y = radius * Math.sin(angle) 来进行绘制,但这是关于x轴对称的,如果遇到正多边形的边数为奇数,而你又希望它是以y轴对称时,可按照下面的方法。

在一般情况下,会使用 x = radius * Math.cos(angle), y = radius * Math.sin(angle) 来进行绘制,但这是关于x轴对称的,如果遇到正多边形的边数为奇数,而你又希望它是以y轴对称时,可按照下面的方法。

1.gif

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

编程的流程图如下

1584789503527091.jpg

使用两个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);
}

大家可以去试试吧。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/duobianxign28309482093480.html

网友评论文明上网理性发言 已有0人参与

发表评论: