小白学canvas-绘制正多边形、五角星

2017-12-11  本文已影响0人  芥末海苔QAQ

绘制正多边形

第一种方法就是发挥强大的数学能力,计算出各个顶点的位置,然后moveTo(),lineTo()。
第二种就是抄抄大神写的正多边形函数

function createPolygon(cxt,n,dx,dy,size){
            cxt.beginPath();
            var degree=(2*Math.PI)/n;
            for (var i=0;i<n;i++){
                var x=Math.cos(i*degree);
                var y=Math.sin(i*degree);
                cxt.lineTo(x*size+dx,y*size+dy);
            }
            cxt.closePath();
        }

creatPolygon(cxt,n,dx,dy,size),n为边数,(dx,dy)为多边形中心点位置,size为中心点到顶点的距离。然后调用creatPolygon()方法

图片.png
关于closePath()

如果画布的子路径是打开的,closePath() 通过添加一条线条连接当前点和子路径起始点来关闭它。
如果子路径已经闭合了,这个方法不做任何事情。
一旦子路径闭合,就不能再为其添加更多的直线或曲线了。要继续向该路径添加,需要通过调用 moveTo() 开始一条新的子路径。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        //封装
        function $$(id){
            return document.getElementById(id);
        }
        window.onload=function(){
            //提取
            var cnv=$$("canvas");
            var cxt=cnv.getContext("2d");
            //绘制正多边形
            createPolygon(cxt,5,125,75,50);
            cxt.fillStyle="red";
            cxt.fill();
        }
        //封装正多边形函数
        function createPolygon(cxt,n,dx,dy,size){
            cxt.beginPath();
            var degree=(2*Math.PI)/n;
            for (var i=0;i<n;i++){
                var x=Math.cos(i*degree);
                var y=Math.sin(i*degree);
                cxt.lineTo(x*size+dx,y*size+dy);
            }
            cxt.closePath();
        }
    </script>
</head>
<body>
    <canvas id="canvas" width="250" height="150" style="border:1px dashed gray"></canvas>
</body>
</html>
正五边形( ̄Q ̄)╯

绘制五角星

先获取顶点坐标,然后连接起来。


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        //封装
        function $$(id){
            return document.getElementById(id);
        }
        window.onload=function(){
            //提取
            var cnv=$$("canvas");
            var cxt=cnv.getContext("2d");
            //绘制五角星
            cxt.beginPath();
            for (var i=0;i<5;i++){
                //+号后的值为中心点坐标值
                cxt.lineTo(Math.cos((18+i*72)*Math.PI/180)*50+125,
                -Math.sin((18+i*72)*Math.PI/180)*50+75);
                cxt.lineTo(Math.cos((54+i*72)*Math.PI/180)*25+125,
                -Math.sin((54+i*72)*Math.PI/180)*25+75);
            }
            cxt.closePath();
            cxt.fillStyle="yellow";//定义填充颜色
            cxt.fill();//填充动作
            cxt.strokeStyle="red";//定义描边颜色
            cxt.stroke();//描边动作
        }
    </script>
</head>
<body>
    <canvas id="canvas" width="250" height="150" style="border:1px dashed gray"></canvas>
</body>
</html>
亮闪闪的五角星★´∀`★
上一篇下一篇

猜你喜欢

热点阅读