html5 canvas繪制矩形和圓形的實例代碼

字號:


    下面小編就為大家?guī)硪黄猦tml5 canvas繪制矩形和圓形的實例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。
    html5 canvas繪制矩形和圓形的實例代碼
    JavaScript Code
    <!DOCTYPE html>   
    <html>   
        <head>   
            <meta charset="UTF-8">   
            <title></title>   
        </head>   
        <body onload="draw(),drawarc()">   
            <!--繪制的步驟:獲取canvas元素->取得上下文->填充與繪制邊框->設(shè)定繪圖樣式-->   
            <!--繪制其他復雜圖形需要使用路徑:開始創(chuàng)建路徑->創(chuàng)建圖形路徑->關(guān)閉路徑->繪制圖形-->   
            <!--eg:繪制矩形-->   
            繪制矩形:<canvas id="ca"></canvas><br />   
            繪制圓形:<canvas id="yuan"></canvas>   
        </body>   
    </html>   
    <script>   
        //繪制矩形   
        function draw(){   
            var canvas=document.getElementById('ca'); //獲取canvas元素   
            if (canvas==null)   
               return false;   
            var context=canvas.getContext('2d'); //取得上下文   
            context.fillStyle='#EEEFF';   //填充顏色   
            context.fillRect(0,0,400,300); //填充矩形 (矩形1)   
            context.fillStyle='red';   
            context.strokeStyle='blue'; //邊框顏色   
            context.lineWidth=1;        //邊框?qū)挾?  
            context.fillRect(50,50,100,100); //填充矩形(內(nèi)部矩形2)   
            context.strokeRect(50,50,100,100); //繪制邊框   
        }   
        //繪制圓形   
       function drawarc(){   
        var canvas2=document.getElementById('yuan'); //獲取canvas元素   
            if (canvas2==null)   
        if(canvas2==null)   
           return false;   
           var context2=canvas2.getContext('2d');  //取得上下文   
           context2.fillStyle='#EEEEEF';   
           context2.fillRect(0,0,400,300);   
           var n=0;   
           for(var i=0;i<10;i++){   
                  context2.beginPath();  //開始創(chuàng)建路徑   
                  context2.arc(i*25,i*25,i*10,0,Math.PI*2,true);  //創(chuàng)建圓形路徑   
                  context2.closePath();  //關(guān)閉路徑   
                  context2.fillStyle='Rgba(255,0,0,0.25)'; //設(shè)置顏色   
                  context2.fill();  //填充圖形   
           }   
    }   
    </script>  
    以上就是小編為大家?guī)淼膆tml5 canvas繪制矩形和圓形的實例代碼的全部內(nèi)容了