以 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>

 

呈現結果如下圖

螢幕擷取畫面 2021-07-12 142100.png

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 虎頭蛇尾 的頭像
    虎頭蛇尾

    虎頭蛇尾的部落格

    虎頭蛇尾 發表在 痞客邦 留言(0) 人氣()