javascript怎么画正五边形?下面本篇文章给大家介绍一下。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
如何用程序来绘制正多边形?
在一般情况下,会使用 x = radius * Math.cos(angle), y = radius * Math.sin(angle) 来进行绘制,但这是关于x轴对称的,如果遇到正多边形的边数为奇数,而你又希望它是以y轴对称时,可按照下面的方法。
如图,正五边形ABCDE关于y轴对称,B与E,C与D互为对称点。A的坐标为(0, r)。 半径OA旋转一个内角θ,便是OB,此时B的坐标为(r·sin0, r·cos0)。继续旋转,可以得到OC、OD、OE等半径,坐标求法与OB的一致,只需把对应的角度依次增加(2π/边数)。
编程的流程图如下
使用两个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中文网 !!