路徑填充
1. 前言
我們之前學習的教程主要內容都以繪制路徑和畫輪廓線為主,今天我們將學習一個新的概念內容:填充路徑。
2. 利用 fill 方法填充路徑
填充路徑,填充的必須是路徑,所以我們得先有路徑才能填充,需要注意,這里的路徑不能是一條線段,最少需要一個兩條邊的折線。下面我們就以案例的形式學習一下“填充”相關的內容。
2.1 填充矩形
我們先用上一小節學習的 rect
方法繪制一個矩形路徑然后填充。
先看整體案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>慕課網Wiki</title>
<style>
#imooc{
border:1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的瀏覽器不支持 HTML5 canvas 標簽</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.strokeStyle="blue";
ctx.lineWidth=8;
ctx.rect(10,10,200,100);
ctx.fill(); //直接填充路徑
</script>
</body>
</html>
運行結果:

我們從案例中可以看到,調用 fill
函數,會使用黑色把整個矩形框填滿,這樣的效果就是填充。當然,我們也可以利用 fillStyle
屬性設定填充顏色。
2.2 設定 fillStyle 屬性
fillStyle
屬性的作用是設定填充內容的顏色,它和設定 strokeStyle
描邊屬性一樣。
先看整體案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>慕課網Wiki</title>
<style>
#imooc{
border:1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的瀏覽器不支持 HTML5 canvas 標簽</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveTo(10,10);
ctx.lineTo(10,100);
ctx.lineTo(200,100);
ctx.closePath();
ctx.fillStyle="#cccccc" // 設定填充顏色
ctx.fill();
</script>
</body>
</html>
運行結果:

我們從案例中可以看到,設定了填充顏色后再調用 fill
函數,會使用設定的顏色把整個路徑填滿。
3. stroke() 和 fill() 對比學習
我們知道,stroke
方法作用是描邊,fill
方法作用是填充,我們來整體再回顧學習一下這兩個方法。
先看整體案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>慕課網Wiki</title>
<style>
#imooc{
border:1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="imooc">您的瀏覽器不支持 HTML5 canvas 標簽</canvas>
<script>
const canvas = document.getElementById('imooc');
const ctx = canvas.getContext('2d');
ctx.moveTo(10,10);
ctx.lineTo(10,100);
ctx.lineTo(200,100);
ctx.lineTo(200,10);
ctx.closePath();
ctx.strokeStyle="blue";
ctx.fillStyle="#ccc";
ctx.lineWidth=8;
ctx.stroke();
ctx.fill();
</script>
</body>
</html>
運行結果:

我們將上面案例的繪圖內容拆分講解:
-
獲取 canvas 的渲染上下文。
const canvas = document.getElementById('imooc'); const ctx = canvas.getContext('2d');
-
繪制一個圖形路徑。
ctx.moveTo(10,10); ctx.lineTo(10,100); ctx.lineTo(200,100); ctx.lineTo(200,10); ctx.closePath();
-
分別設定描邊的顏色和填充的顏色。
ctx.strokeStyle="blue"; ctx.fillStyle="#ccc";
-
描邊和填充。
提示:當設定了描邊寬度以后,這里先描邊后填充和先填充后描邊繪制出來的圖形是不一樣的,后繪制的內容會覆蓋前面繪制的內容。
ctx.stroke(); ctx.fill();
我們從案例中可以看到,路徑的描邊和填充在使用上都是相似的。
4. 方法整理
本小節中我們使用到一個新的方法 fill
。
4.1 fill() 方法
fill()
方法是用于填充當前已存在的路徑的方法,如果沒有設置填充顏色,則默認使用黑色填充。
5. 屬性整理
本小節中我們使用到一個新的屬性 fillStyle
。
5.1 fillStyle 屬性
fillStyle
屬性用于設置填充的顏色,它和 strokeStyle
在使用上是一致的。
ctx.fillStyle = "blue"
ctx.fillStyle = "#cccccc"
ctx.fillStyle = "#ccc"
ctx.fillStyle = "rgb(200, 200, 200)"
ctx.fillStyle = "rgba(200, 200, 200, 0.5)"
ctx.fillStyle = "hsl(0, 100%, 50%)"
ctx.fillStyle = "hsla(0, 100%, 50%, 0.5)"
上面7種寫法都是支持的。
6. 總結
本小節我們主要學習了利用 fill
方法填充一個圖形。