顏色和樣式是通過strokeStyle和fillStyle兩個屬性修改的,它們的默認值都是black,strokeStyle表示畫線(描邊)用的樣式,fillStyle表示填充用的樣式,它們可以被賦予三種類型的值:純色、漸變和模式。
純色
純色有以下三種賦值方法:
- 直接賦予顏色值,包括賦予十六進制和顏色的單詞,例如#323232、red等
- 使用rgb函數賦值,rgb函數有三個十進制(0~255)的參數,分別表示紅、綠、藍的值
- 使用rgba函數賦值,rgba函數在rgb函數的基礎上添加了透明度(alpha),它用第四個參數表示透明度。透明度的取值範圍爲【0,1】,其中,0表示完全透明,1表示完全不透明。
示例:
<body>
<canvas id='c2d'>瀏覽器不支持canvas</canvas>
<script>
const canvas = document.getElementById('c2d');
if (canvas.getContext) {
let ctx = canvas.getContext('2d');
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.rect(0,0,20,20);
ctx.fill();
ctx.fillStyle = "rgb(249,27,27)";
ctx.beginPath();
ctx.rect(20,20,20,20);
ctx.fill();
ctx.fillStyle = "rgb(249,27,27, 0.5)";
ctx.beginPath();
ctx.rect(40,40,20,20);
ctx.fill();
}
</script>
</body>
漸變
漸變的顏色是通過CanvasGradient對象來表示的,它可以使用下面兩個方法來創建:
- createLinearGradient(x0,y0,x1,y1): 創建線性漸變
- createRadialGradient(x0,y0,x1,y1,r1): 創建徑向漸變,也就是散漸變
CanvasGradient對象包含一個addColorStop方法,用來添加漸變的顏色控制點,語法如下:
addColorStop(offset,color)
offset用於設置控制點,取值範圍【0,1】;color用於設置控制點的顏色。
示例:
<body>
<canvas id='c2d'>瀏覽器不支持canvas</canvas>
<script>
const canvas = document.getElementById('c2d');
if (canvas.getContext) {
let ctx = canvas.getContext('2d');
let lineGradient = ctx.createLinearGradient(20,20,100,150);
lineGradient.addColorStop(0, 'red');
lineGradient.addColorStop(0.5, 'rgba(255,255,0,0.7)');
lineGradient.addColorStop(1, '#ff6d00');
ctx.fillStyle = lineGradient;
ctx.beginPath();
ctx.arc(50,50,30,0,2*Math.PI);
ctx.fill();
let radiaGradient = ctx.createRadialGradient(130,50,10,130,50,30);
radiaGradient.addColorStop(0,'rgba(255,204,205,0.3)');
radiaGradient.addColorStop(0.5,'#ffff00');
radiaGradient.addColorStop(1,'#ff6d00');
ctx.fillStyle = radiaGradient;
ctx.fillRect(100,20,60,60);
}
</script>
</body>
模式
模式使用CanvasPattern對象來表示的,它使用createPattern方法來創建,語法如下:
createPattern(image,repetition);
參數中,image爲CanvasImageSource類型,它可以是html中的img節點、video節點、canvas節點或者CanvasRenderingContext2D對象。repetion爲重複方式,它可以取下面4個值:
- repeat: 水平和豎直兩個方向重複
- repeat-x: 水平重複
- repeat-y: 豎直重複
- no-repeat: 不重複
模式的用法就好像使用圖片作爲畫筆繪圖,其中repetition屬性跟css中的background-repeat屬性類似。
示例:
<body>
<canvas id='c2d'>瀏覽器不支持canvas</canvas>
<script>
const canvas = document.getElementById('c2d');
if (canvas.getContext) {
let ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function () {
var pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 400, 400);
};
}
</script>
</body>
如果我的博客對你有幫助、如果你喜歡我的博客內容,請 “點贊” “評論” “收藏” 一鍵三連哦!
聽說 👉 點贊 👈 的人運氣不會太差,每一天都會元氣滿滿哦 嘿嘿!!! ❤️ ❤️ ❤️
大家的支持就是我堅持下去的動力。點贊後不要忘了👉 關注 👈我哦!