以 javascript 畫出「五芒星」
<html>
<body>
<canvas id="canvas" width="600" height="600" style="border:1px solid #c3c3c3;">
</canvas>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById("canvas");
var context=canvas.getContext("2d");
//繪製和畫布一樣大小的黑色矩形
context.fillStyle = "black";
context.fillRect(0,0,canvas.width,canvas.height);
//隨機大圓半徑
var r = 100;
var x =0.5* canvas.width;
var y =0.5* canvas.height;
//隨機旋轉角0-360
var a = 360;
drawstar(context,x,y,r,r/2.5,a);}
//定義五角星函式,注意在javascript中三角函式要求角度轉換為弧度,x,y為五角星的偏移量,rot為圖形旋轉角度
function drawstar(cxt,x,y,outerR,innnerR,rot){
cxt.beginPath();
for(var i = 0;i < 5;i ++){
cxt.lineTo(Math.cos((18 + i * 72 - rot)/180 *Math.PI)*outerR + x,-Math.sin((18 + i * 72 - rot)/180*Math.PI)*outerR + y);
cxt.lineTo(Math.cos((54 + i * 72 - rot)/180 *Math.PI)*innnerR + x,-Math.sin((54 + i * 72 - rot)/180*Math.PI)*innnerR + y);
}
cxt.closePath();
//狀態
cxt.fillStyle = "";
cxt.strokeStyle = "#fb5";
cxt.lineWidth = 3;
cxt.lineJoin = "round";
//執行
cxt.fill();
cxt.stroke();
}
</script>
</body>
</html>
呈現結果如下圖