HTML canvas createLinearGradient() 方法
實例
定義從黑到白的漸變(從左向右),作為矩形的填充樣式:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);
嘗試一下»
瀏覽器支持
Internet Explorer 9、Firefox、Opera、Chrome 和Safari 支持createLinearGradient() 方法。
注意: Internet Explorer 8及之前的版本不支持<canvas>元素。
定義和用法
createLinearGradient() 方法創建線性的漸變對象。
漸變可用於填充矩形、圓形、線條、文本等等。
提示:請使用該對像作為strokeStyle或fillStyle屬性的值。
提示:請使用addColorStop()方法規定不同的顏色,以及在gradient對像中的何處定位顏色。
JavaScript 語法: | context.createLinearGradient(x0,y0,x1,y1); |
---|
參數值
参数 | 描述 |
---|---|
x0 | 渐变开始点的 x 坐标 |
y0 | 渐变开始点的 y 坐标 |
x1 | 渐变结束点的 x 坐标 |
y1 | 渐变结束点的 y 坐标 |
更多實例
實例
定義一個漸變(從上到下)作為矩形的填充樣式:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0,170);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0,170);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);
嘗試一下»
實例
定義一個從黑到紅再到白的漸變,作為矩形的填充樣式:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,170,0);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(0.5,"red");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,170,0);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(0.5,"red");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);
嘗試一下»
HTML canvas參考手冊