當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML <canvas>用法及代碼示例


HTML中的<canvas>標記用於使用JavaScript在網頁上繪製圖形。它可用於繪製路徑,框,文本,漸變和添加圖像。默認情況下,它不包含邊框和文本。

注意:<canvas>標記是HTML5中的新標記。

用法:

<canvas id = "script"> Contents... </canvas>

屬性:標簽接受上麵提到和下麵描述的兩個屬性。

範例1:



HTML

<!DOCTYPE html> 
<html> 
    <body> 
          
        <!-- canvas Tag starts here -->
        <canvas id = "GeeksforGeeks" width = "200" 
            height = "100" style = "border:1px solid black"> 
        </canvas> 
        <!-- canvas Tag ends here -->
          
    </body> 
</html>

輸出:

範例2:

HTML

<!DOCTYPE html> 
<html> 
      
    <body> 
        <!-- HTML code to illustrate canvas tag -->
        <canvas id = "geeks" height = "200" width = "200"
            style = "border:1px solid black"> 
        </canvas> 
          
        <script> 
            var c = document.getElementById("geeks"); 
            var cx = c.getContext("2d"); 
            cx.beginPath(); 
            cx.arc(100, 100, 90, 0, 2 * Math.PI); 
            cx.stroke(); 
        </script> 
            
    </body> 
</html>

輸出:

範例3:

HTML

<!DOCTYPE html> 
<html> 
    <body> 
          
        <!-- canvas tag starts here -->
        <canvas id = "geeks" width = "200" height = "200"
            style = "border:1px solid black"> 
        </canvas> 
        <!-- canvas tag ends here -->
          
        <script> 
            var c=document.getElementById("geeks"); 
            var cx = c.getContext("2d"); 
            var grd = cx.createRadialGradient(100,  
                            100, 5, 100, 100, 100); 
            grd.addColorStop(0, "red"); 
            grd.addColorStop(1, "green"); 
            cx.fillStyle = grd; 
            cx.fillRect(0, 0, 200, 200); 
        </script> 
        
    </body> 
</html>

輸出:

支持的瀏覽器:

  • 穀歌瀏覽器4.0
  • Internet Explorer 9.0
  • Firefox 2.0
  • Opera 9.0
  • Safari 3.1




相關用法


注:本文由純淨天空篩選整理自sheyakhare1999大神的英文原創作品 HTML <canvas> Tag。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。