代码绘制六角形
绘制一个多角形
在as中实现:
public static function drawStart(g:Graphics,num:uint,r:Number,
fillColor:uint = 0xFF0000):void{
var points:Array = [];
var perAngle:Number = 180 / num;
for(var i:int = 0;i<num*2;i++){
if(i % 2){
points.push(PointUtil.getPolarPoint(perAngle*i,r/2));
}else{
points.push(PointUtil.getPolarPoint(perAngle*i,r));
}
}
g.clear();
g.beginFill(fillColor,1);
g.moveTo(points[0].x,points[0].y);
for(var i:int = 1;i<points.length;i++){
g.lineTo(points[i].x,points[i].y);
}
g.lineTo(points[0].x,points[0].y);
g.endFill();
}
在js中实现:
//简单模拟jquery的$函数
function $(documentId){
return document.getElementById(documentId);
};
function getPoint(angle,l){
var radians = angle * Math.PI / 180;
var x,y;
x = l * Math.cos(radians);
y = l * Math.sin(radians);
return {
x : x,
y : y
};
};
/** 绘制星星
* @param cId the canvas id
* @param num 外顶点数目
* @param r 半径长度
* @param fillcolor 填充颜色
**/
function drawStart (cId,num,r,fillcolor) {
var c = $(cId);
var ctx = c.getContext("2d");
var points = [],perAngle = 180 / num;
for(var i = 0;i<num*2;i++){
if (i % 2) {
points.push(getPoint(perAngle * i,r/2));
} else{
points.push(getPoint(perAngle * i,r));
};
};
ctx.beginPath();
ctx.strokeStyle = 0;
ctx.fillStyle = fillcolor;
ctx.moveTo(points[0].x + offsetX,points[0].y + offsetY);
for(var j = 1;j<points.length;j++){
ctx.lineTo(points[j].x + offsetX,points[j].y + offsetY);
}
ctx.lineTo(points[0].x + offsetX,points[0].y + offsetY);
ctx.closePath();
ctx.stroke();
ctx.fill();
};
var offsetX = 40;
var offsetY = 40;
drawStart("canvas",6,15,"#ff0000");