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


HTML canvas fillStyle用法及代碼示例


canvas fillStyle屬性用於設置或返回用於填充圖形的顏色,漸變或圖案。

樣式:

context.fillStyle=color|gradient|pattern;

屬性值:


  • color:用於設置圖形的填充顏色。 canvas fillStyle屬性的默認值為black。
  • gradient:用於設置漸變對象以填充圖形。漸變對象是線性或徑向的。
  • pattern:用於設置圖案以填充圖形。

示例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML canvas fillStyle property 
    </title> 
</head> 
  
<body> 
    <canvas id="GFG" 
            width="500" 
            height="300"> 
  </canvas> 
  
    <script> 
        var x = document.getElementById("GFG"); 
        var contex = x.getContext("2d"); 
        
        // set fillStyle color green. 
        contex.fillStyle = "green"; 
        contex.fillRect(50, 50, 350, 200); 
        contex.stroke(); 
    </script> 
  
</body> 
  
</html>

輸出:

示例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML canvas fillStyle property 
    </title> 
</head> 
  
<body> 
    <canvas id="GFG" 
            width="500"
            height="300"> 
  </canvas> 
  
    <script> 
        var x =  
            document.getElementById("GFG"); 
        var contex =  
            x.getContext("2d"); 
        var gr =  
            contex.createLinearGradient(50, 0, 350, 0); 
        gr.addColorStop(0, "green"); 
        gr.addColorStop(1, "white"); 
        contex.fillStyle = gr; 
        contex.fillRect(50, 50, 350, 200); 
        contex.stroke(); 
    </script> 
</body> 
  
</html>

輸出:

示例3:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML canvas fillStyle property 
    </title> 
</head> 
  
<body> 
    <canvas id="GFG"
            width="500"
            height="300"> 
  </canvas> 
  
    <script> 
        var x =  
            document.getElementById("GFG"); 
        
        var contex = 
            x.getContext("2d"); 
        
        var gr = 
            contex.createLinearGradient(0, 100, 0, 200); 
        gr.addColorStop(0, "green"); 
        gr.addColorStop(1, "yellow"); 
        contex.fillStyle = gr; 
        contex.fillRect(50, 50, 350, 200); 
        contex.stroke(); 
    </script> 
</body> 
  
</html>

輸出:

支持的瀏覽器:

  • 穀歌瀏覽器
  • Internet Explorer 9.0
  • 火狐瀏覽器
  • 蘋果瀏覽器
  • Opera


相關用法


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