HTML canvas createLinearGradient() Metodo

❮ Riferimento tela HTML

Esempio

Definisci un gradiente (da sinistra a destra) che va dal nero al bianco, come stile di riempimento per il rettangolo:

Il tuo browser non supporta il canvastag HTML5.

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

Supporto del browser

I numeri nella tabella specificano la prima versione del browser che supporta completamente il metodo.

Method
createLinearGradient() Yes 9.0 Yes Yes Yes

Definizione e utilizzo

Il metodo createLinearGradient() crea un oggetto gradiente lineare.

Il gradiente può essere utilizzato per riempire rettangoli, cerchi, linee, testo, ecc.

Suggerimento: utilizza questo oggetto come valore per le proprietà strokeStyle o fillStyle .

Suggerimento: utilizza il metodo addColorStop() per specificare colori diversi e dove posizionare i colori nell'oggetto sfumatura.

sintassi JavaScript: contesto .createLinearGradient( x0,y0,x1,y1 );

Valori dei parametri

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

Altri esempi

Esempio

Definisci una sfumatura (dall'alto in basso) come stile di riempimento per il rettangolo:

Il tuo browser non supporta il tag canvas.

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

Esempio

Definisci un gradiente che va dal nero, al rosso, al bianco, come stile di riempimento per il rettangolo:

Il tuo browser non supporta il tag canvas.

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

❮ Riferimento tela HTML