Phương thức canvas createLinearGradient () HTML

❮ Tham chiếu HTML Canvas

Thí dụ

Xác định một gradient (từ trái sang phải) chuyển từ đen sang trắng, làm kiểu tô cho hình chữ nhật:

YourbrowserdoesnotsupporttheHTML5canvastag.

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);

Hỗ trợ trình duyệt

Các số trong bảng chỉ định phiên bản trình duyệt đầu tiên hỗ trợ đầy đủ phương pháp này.

Method
createLinearGradient() Yes 9.0 Yes Yes Yes

Định nghĩa và Cách sử dụng

Phương thức createLinearGradient () tạo một đối tượng gradient tuyến tính.

Gradient có thể được sử dụng để tô các hình chữ nhật, hình tròn, đường thẳng, văn bản, v.v.

Mẹo: Sử dụng đối tượng này làm giá trị cho thuộc tính strokeStyle hoặc fillStyle .

Mẹo: Sử dụng phương thức addColorStop () để chỉ định các màu khác nhau và vị trí các màu trong đối tượng gradient.

Cú pháp JavaScript: context .createLinearGradient ( x0, y0, x1, y1 );

Giá trị tham số

Parameter Description
x0 The x-coordinate of the start point of the gradient
y0 The y-coordinate of the start point of the gradient
x1 The x-coordinate of the end point of the gradient
y1 The y-coordinate of the end point of the gradient

Các ví dụ khác

Thí dụ

Xác định một gradient (từ trên xuống dưới) làm kiểu tô cho hình chữ nhật:

Yourbrowserdoesnotsupportthecanvastag.

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);

Thí dụ

Xác định một gradient chuyển từ đen, sang đỏ, sang trắng, làm kiểu tô cho hình chữ nhật:

Yourbrowserdoesnotsupportthecanvastag.

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);

❮ Tham chiếu HTML Canvas