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

❮ Tham chiếu HTML Canvas

Thí dụ

Xác định một gradient 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
addColorStop() Yes 9.0 Yes Yes Yes

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

Phương thức addColorStop () chỉ định màu sắc và vị trí trong một đối tượng gradient.

Phương thức addColorStop () được sử dụng cùng với createLinearGradient () hoặc createRadialGradient () .

Lưu ý: Bạn có thể gọi phương thức addColorStop () nhiều lần để thay đổi gradient. Nếu bạn bỏ qua phương pháp này cho các đối tượng gradient, gradient sẽ không hiển thị. Bạn cần tạo ít nhất một điểm dừng màu để có một gradient có thể nhìn thấy được.

Cú pháp JavaScript: gradient .addColorStop ( dừng , màu );

Giá trị tham số

Parameter Description Play it
stop A value between 0.0 and 1.0 that represents the position between start and end in a gradient
color A CSS color value to display at the stop position

Các ví dụ khác

Thí dụ

Xác định một gradient với nhiều phương thức addColorStop ():

Yourbrowserdoesnotsupportthecanvastag.

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("0.3", "magenta");
grd.addColorStop("0.5", "blue");
grd.addColorStop("0.6", "green");
grd.addColorStop("0.8", "yellow");
grd.addColorStop(1, "red");

ctx.fillStyle = grd;
ctx.fillRect(20, 20, 150, 100);

❮ Tham chiếu HTML Canvas