Thuộc tính kiểu tô màu canvas
Ví dụ
Xác định màu tô màu đỏ cho hình chữ nhật:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Thuộc tính fillStyle
đặt hoặc trả về màu, độ chuyển màu hoặc mẫu được sử dụng để tô màu cho bản vẽ.
Giá trị mặc định là #000000 (màu đen đặc).
Xem thêm:
Thuộc tính StrokeStyle (Đặt màu/kiểu nét)
Phương thức fillRect() (Vẽ hình chữ nhật đầy)
Phương thức orth() (Vẽ một hình chữ nhật không tô màu)
Cú pháp
bối cảnh .fillStyle = color | độ dốc | mẫu |
Giá trị tài sản
Value | Description | Play it |
---|---|---|
color | A CSS color value that indicates the fill color of the drawing. Default value is #000000 | Play it » |
gradient | A gradient object ( linear or radial ) used to fill the drawing | |
pattern | A pattern object to use to fill the drawing |
Thêm ví dụ
Ví 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:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const 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);
Hãy tự mình thử »Ví dụ
Xác định một gradient (từ trái sang phải) làm kiểu tô màu cho hình chữ nhật:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const my_gradient = ctx.createLinearGradient(0, 0, 170, 0);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);
Hãy tự mình thử »Ví 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:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const 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);
Hãy tự mình thử »Hình ảnh sử dụng:
Ví dụ
Sử dụng hình ảnh để điền vào bản vẽ:
JavaScript:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const img = document.getElementById("lamp");
const pat = ctx.createPattern(img, "repeat");
ctx.rect(0, 0, 150, 100);
ctx.fillStyle = pat;
ctx.fill();
Hãy tự mình thử »Hỗ trợ trình duyệt
Phần tử <canvas>
là tiêu chuẩn HTML5 (2014).
fillStyle()
được hỗ trợ trong tất cả các trình duyệt hiện đại:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |