Home > Web Front-end > H5 Tutorial > Example code for drawing rectangles and circles on html5 canvas

Example code for drawing rectangles and circles on html5 canvas

黄舟
Release: 2017-02-24 14:06:36
Original
1377 people have browsed it

html5 canvas drawing rectangle and circle example code

<!DOCTYPE html>   

    <html>   

        <head>   

            <meta charset="UTF-8">   

            <title></title>   

        </head>   

        <body onload="draw(),drawarc()">   

            <!--绘制的步骤:获取canvas元素->取得上下文->填充与绘制边框->设定绘图样式-->   

            <!--绘制其他复杂图形需要使用路径:开始创建路径->创建图形路径->关闭路径->绘制图形-->   

            <!--eg:绘制矩形-->   

            绘制矩形:<canvas id="ca"></canvas><br />   

            绘制圆形:<canvas id="yuan"></canvas>   

        </body>   

    </html>   

    <script>   

        //绘制矩形   

        function draw(){   

            var canvas=document.getElementById(&#39;ca&#39;); //获取canvas元素   

            if (canvas==null)   

               return false;   

            var context=canvas.getContext(&#39;2d&#39;); //取得上下文   

            context.fillStyle=&#39;#EEEFF&#39;;   //填充颜色   

            context.fillRect(0,0,400,300); //填充矩形 (矩形1)   

            context.fillStyle=&#39;red&#39;;   

            context.strokeStyle=&#39;blue&#39;; //边框颜色   

            context.lineWidth=1;        //边框宽度   

            context.fillRect(50,50,100,100); //填充矩形(内部矩形2)   

            context.strokeRect(50,50,100,100); //绘制边框   

               

        }   

        //绘制圆形   

       function drawarc(){   

        var canvas2=document.getElementById(&#39;yuan&#39;); //获取canvas元素   

            if (canvas2==null)   

        if(canvas2==null)   

           return false;   

           var context2=canvas2.getContext(&#39;2d&#39;);  //取得上下文   

           context2.fillStyle=&#39;#EEEEEF&#39;;   

           context2.fillRect(0,0,400,300);   

           var n=0;   

           for(var i=0;i<10;i++){   

                  context2.beginPath();  //开始创建路径   

                  context2.arc(i*25,i*25,i*10,0,Math.PI*2,true);  //创建圆形路径   

                  context2.closePath();  //关闭路径   

                  context2.fillStyle=&#39;Rgba(255,0,0,0.25)&#39;; //设置颜色   

                  context2.fill();  //填充图形   

           }   

    }   

           

           

    </script>
Copy after login



## The above is the html5 canvas drawing rectangle and circle The content of the example code, please pay attention to the PHP Chinese website (www.php.cn) for more related content!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template