繪制正多邊形
第一種方法就是發(fā)揮強大的數(shù)學(xué)能力,計算出各個頂點的位置,然后moveTo(),lineTo()。
第二種就是抄抄大神寫的正多邊形函數(shù)
function createPolygon(cxt,n,dx,dy,size){
cxt.beginPath();
var degree=(2*Math.PI)/n;
for (var i=0;i<n;i++){
var x=Math.cos(i*degree);
var y=Math.sin(i*degree);
cxt.lineTo(x*size+dx,y*size+dy);
}
cxt.closePath();
}
creatPolygon(cxt,n,dx,dy,size),n為邊數(shù),(dx,dy)為多邊形中心點位置,size為中心點到頂點的距離。然后調(diào)用creatPolygon()方法

圖片.png
關(guān)于closePath()
如果畫布的子路徑是打開的,closePath() 通過添加一條線條連接當前點和子路徑起始點來關(guān)閉它。
如果子路徑已經(jīng)閉合了,這個方法不做任何事情。
一旦子路徑閉合,就不能再為其添加更多的直線或曲線了。要繼續(xù)向該路徑添加,需要通過調(diào)用 moveTo() 開始一條新的子路徑。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
//封裝
function $$(id){
return document.getElementById(id);
}
window.onload=function(){
//提取
var cnv=$$("canvas");
var cxt=cnv.getContext("2d");
//繪制正多邊形
createPolygon(cxt,5,125,75,50);
cxt.fillStyle="red";
cxt.fill();
}
//封裝正多邊形函數(shù)
function createPolygon(cxt,n,dx,dy,size){
cxt.beginPath();
var degree=(2*Math.PI)/n;
for (var i=0;i<n;i++){
var x=Math.cos(i*degree);
var y=Math.sin(i*degree);
cxt.lineTo(x*size+dx,y*size+dy);
}
cxt.closePath();
}
</script>
</head>
<body>
<canvas id="canvas" width="250" height="150" style="border:1px dashed gray"></canvas>
</body>
</html>

正五邊形( ̄Q ̄)╯
繪制五角星
先獲取頂點坐標,然后連接起來。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
//封裝
function $$(id){
return document.getElementById(id);
}
window.onload=function(){
//提取
var cnv=$$("canvas");
var cxt=cnv.getContext("2d");
//繪制五角星
cxt.beginPath();
for (var i=0;i<5;i++){
//+號后的值為中心點坐標值
cxt.lineTo(Math.cos((18+i*72)*Math.PI/180)*50+125,
-Math.sin((18+i*72)*Math.PI/180)*50+75);
cxt.lineTo(Math.cos((54+i*72)*Math.PI/180)*25+125,
-Math.sin((54+i*72)*Math.PI/180)*25+75);
}
cxt.closePath();
cxt.fillStyle="yellow";//定義填充顏色
cxt.fill();//填充動作
cxt.strokeStyle="red";//定義描邊顏色
cxt.stroke();//描邊動作
}
</script>
</head>
<body>
<canvas id="canvas" width="250" height="150" style="border:1px dashed gray"></canvas>
</body>
</html>

亮閃閃的五角星★′?`★