要幫圖形上色,Canvas 2D 提供兩個核心屬性:fillStyle 負責填色,strokeStyle 負責描邊。兩者接受的值都是 CSS 顏色字串、漸層物件或圖樣物件;若從未設定,預設是黑色(#000000)。
ctx.fillStyle = "orange"; ctx.fillStyle = "#FFA500"; ctx.fillStyle = "rgb(255,165,0)"; ctx.fillStyle = "rgba(255,165,0,1)";
上面四種寫法結果完全相同,挑順手的即可。要留意兩點:一是舊版 Gecko 引擎對 CSS3 顏色語法的支援並不完整,例如 hsl(100%,25%,0)、rgb(0,100%,0) 這類寫法在當時會失效;二是樣式具有「黏著性」,設定之後會一直沿用,直到你再次賦值。想讓每個圖形擁有不同顏色,就必須在每次繪製前重設。
用兩層迴圈搭配 RGB 通道運算,只讓紅、綠兩個通道遞減、藍色固定為 0,就能得到一整片暖色階梯。調整通道的變化幅度,等於在調色盤的取樣密度。
<script type="text/javascript">
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' + Math.floor(255 - 42.5 * j) + ',0)';
ctx.fillRect(j * 25, i * 25, 25, 25);
}
}
}
</script>
效果預覽:https://hovertree.com/texiao/html5/canvas/1/
邏輯幾乎一樣,只是把填色換成描邊,並用 arc 畫圓。這也說明了 Canvas 的另一個特性:填色與描邊是兩條獨立的管線,同一個路徑可以只填、只描,或兩者都來。
<script type="text/javascript">
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 6; i++) {
for (var j = 0; j < 6; j++) {
ctx.strokeStyle = 'rgb(0,' + Math.floor(255 - 42.5 * i) + ',' + Math.floor(255 - 42.5 * j) + ')';
ctx.beginPath();
ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true);
ctx.stroke();
}
}
}
</script>
效果預覽:https://hovertree.com/texiao/html5/canvas/2/
半透明有兩條路。第一條是 globalAlpha,它會影響之後所有繪製操作,特別適合一次畫很多相同透明度的圖形:
ctx.globalAlpha = 0.2;
第二條是把 alpha 寫進顏色本身,實務上更好控管,因為不必擔心全域狀態被沿用:
ctx.strokeStyle = "rgba(255,0,0,0.5)"; ctx.fillStyle = "rgba(255,0,0,0.5)";
rgba() 的第四個參數就是透明度,範圍 0.0(全透明)到 1.0(全不透明)。
先鋪一塊四色背景,把 globalAlpha 設為 0.2,再畫一串半徑遞增的圓。由於每次繪製都會再疊上一層,圓越多、中心就越被覆蓋,最終形成自然的放射狀漸層。把迴圈次數加大,背景中心會完全消失。
ctx.fillStyle = '#FD0'; ctx.fillRect(0, 0, 75, 75);
ctx.fillStyle = '#6C0'; ctx.fillRect(75, 0, 75, 75);
ctx.fillStyle = '#09F'; ctx.fillRect(0, 75, 75, 75);
ctx.fillStyle = '#F30'; ctx.fillRect(75, 75, 150, 150);
ctx.fillStyle = '#FFF';
ctx.globalAlpha = 0.2;
for (var i = 0; i < 7; i++) {
ctx.beginPath();
ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true);
ctx.fill();
}