canvas五角星(五星紅旗)繪製

效果圖

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>canvas繪製五星紅旗</title>
    <Style>
        #starCanvas{
            /*border: 1px solid blue;*/
        }
    </Style>
</head>
<body>
    <div>
        <canvas id="starCanvas" width="450" height="300">
        </canvas>
    </div>
    <script>
        window.οnlοad=function(){
            fiveStar();//調用五星紅旗函數
        }
        function fiveStar(){//五星紅旗函數
            var cxt = document.getElementById("starCanvas").getContext('2d');//獲取畫布
            cxt.beginPath();
            cxt.fillStyle="#F40002";
            cxt.fillRect(0,0,450,300);
            cxt.closePath();
            cxt.translate(75,75);
            //大的五角星
            cxt.save();
            cxt.rotate(Math.PI*2/5/2);//正向上
            strowStar(cxt,40);
            cxt.restore();
            //繪製四個小五角星
            cxt.save();
            cxt.translate(80,-50);
            strowStar(cxt,10);
            cxt.restore();
            cxt.save();
            cxt.translate(110,-10);
            strowStar(cxt,10);
            cxt.restore();
            cxt.save();
            cxt.translate(110,30);
            strowStar(cxt,10);
            cxt.restore();
            cxt.save();
            cxt.translate(80,70);
            strowStar(cxt,10);
            cxt.restore();
        }
        //繪製五角星函數
        function strowStar(cxt,r,R){//r內切圓半徑,R外切圓半徑
            cxt.save();
            cxt.beginPath();
            cxt.moveTo(0,r);//第一個點爲五角星的上頂點(內切圓半徑r)
            for(var i=0;i<9;i++){
                cxt.rotate(Math.PI/5);//30度
                /*頂點對應的每個角度:54度=360度/5(五個角)
                求出每個外頂點(內頂點)對應的座標(x,y)
                基礎:canvas中向右向下爲正,直角中內頂點:sin(54度)=y/r,cos(54度)=x/r
                */
                if(i%2==0){//偶數,外頂點。
                    cxt.lineTo(Math.cos( (54+72*i)/180*Math.PI) * r,Math.sin((54+72*i)/180*Math.PI) * r);
                }else{//奇數內頂點
                    cxt.lineTo(Math.cos( (18+72*i)/180*Math.PI) * R, Math.sin((18+72*i)/180*Math.PI) * R);
                }
            }
            cxt.closePath();
            cxt.fillStyle="#FAF408";
            cxt.fill();
            cxt.restore();
        }

    </script>
</body>
</html>
發佈了28 篇原創文章 · 獲贊 8 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章