Canvas(1)

156 阅读1分钟

第一周

画一个入门五角星

我们可以用最基本的lineTo()和 moveTo()把五角星绘制出来。根据下图的分析,我们可以知道<BOA=36deg,<AOX=18deg,<BOX=54deg,然后结合三角函数,就很容易得出五角星各个顶点的坐标。

<html>
    <head>
        <title>五角星</title>
        <meta charset="utf-8"/>
        <script>
            function ?(id){
                return document.getElementById(id)
            }
            window.onload = function(){
                var cnv = ?("canvas")
                var cxt = cnv.getContext("2d")
                
                cxt.beginPath()
                for(let i=0 ; i<5;i++){
                    cxt.lineTo(Math.cos((18+i*72)*Math.PI/180)*50+100,-Math.sin((18+i*72)*Math.PI/180)*50+100)
                    cxt.lineTo(Math.cos((54+i*72)*Math.PI/180)*25+100,-Math.sin((54+i*72)*Math.PI/180)*25+100)
                }
                cxt.lineWidth="3";   
                cxt.fillStyle = "#F6F152";   
                cxt.strokeStyle = "#F5270B";   
                cxt.fill();   
                cxt.closePath();
                cxt.stroke();

            }
            }
        </script>
    </head>
    <body>
        <canvas id="canvas" width="200" height="150" style="border:1px dashed #ddd"></canvas>
    </body>
</html>

ps: 这个是72的由来,在五角星的内外画两个圆,五角星有五个角,360/5=72度