利用html5畫出五角星畫出星空
阿新 • • 發佈:2019-02-17
原始碼:
<!DOCTYPE HTML> <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); //呼叫構造五角星函式,並隨機產生多個五角星 for(var i = 0;i < 130;i++){ //隨機大圓半徑 var r = Math.random() * 10 + 10; var x =Math.random() * canvas.width; var y =Math.random() * canvas.height; //隨機旋轉角0-360 var a =Math.random() * 360; drawstar(context,x,y,r,r/2.0,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 = "#fd5"; cxt.strokeStyle = "#fb5"; cxt.lineWidth = 3; cxt.lineJoin = "round"; //執行 cxt.fill(); cxt.stroke(); } </script> </body> </html>