HTML Canvas 漸變

畫布 - 漸變

漸變可用于填充矩形、圓形、線條、文本等。畫布上的形狀并不限于純色。

有兩種不同類型的漸變:

  • createLinearGradient(x,y,x1,y1) - 創建線性漸變
  • createRadialGradient(x,y,r,x1,y1,r1) - 創建徑向/圓形漸變

一旦我們有了漸變對象,就必須添加兩個或更多色標。

addColorStop() 方法規定顏色的停止點及其沿漸變的位置。漸變位置可以是 0 到 1 之間的任意位置。

要使用漸變,請將 fillStyle 或 strokeStyle 屬性設置為漸變,然后繪制形狀(矩形、文本或線條)。

Canvas - Gradients

使用 createLinearGradient()

實例

創建線性漸變。用漸變填充矩形:

Your browser does not support the HTML5 canvas tag.

JavaScript:

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// 創建漸變
const grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// 用漸變填充
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

親自試一試

使用 createRadialGradient():

實例

創建徑向/圓形漸變。用漸變填充矩形:

Your browser does not support the HTML5 canvas tag.

JavaScript:

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// 創建漸變
const grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// 用漸變填充
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

親自試一試

另請參閱:

CodeW3C.com 的完整 Canvas 參考手冊