CanvasGradient: phương thức addColorStop()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available in Web Workers.
CanvasGradient.addColorStop() thêm một điểm dừng màu mới, được xác định bởi offset và color, vào một gradient canvas cho trước.
Cú pháp
js
addColorStop(offset, color)
Tham số
Giá trị trả về
Không có (undefined).
Ngoại lệ
IndexSizeErrorDOMException-
Ném ra nếu
offsetkhông nằm giữa 0 và 1, bao gồm cả hai đầu. SyntaxErrorDOMException-
Ném ra nếu
colorkhông thể được phân tích cú pháp thành giá trị CSS<color>.
Ví dụ
>Thêm các điểm dừng vào dải màu chuyển sắc
Ví dụ này dùng phương thức addColorStop để thêm các điểm dừng vào một đối tượng CanvasGradient tuyến tính. Sau đó dải màu chuyển sắc được dùng để tô một hình chữ nhật.
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "green");
gradient.addColorStop(0.7, "white");
gradient.addColorStop(1, "pink");
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
Kết quả
Thông số kỹ thuật
| Specification |
|---|
| HTML> # dom-canvasgradient-addcolorstop-dev> |
Tương thích trình duyệt
Xem thêm
- Giao diện định nghĩa phương thức này:
CanvasGradient CanvasRenderingContext2D.createLinearGradient()CanvasRenderingContext2D.createRadialGradient()