html代码设置五边形,javascript怎么画正五边形?

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

77b5352264de87f6fde1ed1421e5f319.png

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

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

9a12bede90d9f23bd2af1e743cd73480.gif

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

编程的流程图如下

788ef81dc8db5ea477a3e14397c5ee7a.png

使用两个javascript文件:

Polygon.js —— 正多边形的类,在构造函数中求得所有的顶点,放在数组verticesvar 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前端知识,请查阅 HTML中文网 !!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值