Categories
Web development

HTML Canvas Gradients

The HTML canvas gradient can be used to fill shapes (like circles, squares, rectangles, lines, text, etc.).

HTML5 canvas gradients

You can create two different types of gradients:

createLinearGradient(x,y,x1,y1) – creates a linear gradient.

Syntax:

context.createLinearGradient(x0,y0,x1,y1);

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="square-3" width="200" height="200" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("square-3");
var ctx = c.getContext("2d");
var createGradient = ctx.createLinearGradient(0, 0, 150, 0);
createGradient.addColorStop(0, "#e76f51");
createGradient.addColorStop(0.5, "#f4a261");
createGradient.addColorStop(1, "#e9c46a");
ctx.fillStyle = createGradient;
ctx.fillRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


Where:

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 endpoint of the gradient.

y1 – the y-coordinate of the endpoint of the gradient.

createRadialGradient(x,y,r,x1,y1,r1) – creates a radial/circular gradient.

Syntax:

context.createRadialGradient(x0,y0,r0,x1,y1,r1);

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="radialGradient" width="200" height="200" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("radialGradient");
var ctx = c.getContext("2d");
var grd = ctx.createRadialGradient(100,100,30, 100,100,70);
grd.addColorStop(0, "#e76f51");
grd.addColorStop(1, "#e9c46a");
ctx.fillStyle = grd;
ctx.fillRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


x0 – the x-coordinate of the starting circle of the gradient.

y0 – the y-coordinate of the starting circle of the gradient.

r0 – the radius of the starting circle.

x1 – the x-coordinate of the ending circle of the gradient.

y1 – the y-coordinate of the ending circle of the gradient.

r1 – the radius of the ending circle.

To define different colors add two or more color stops. To create the color stops use the addColorStop():

Syntax:

gradient.addColorStop(stop,color);

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="colorStops" width="200" height="200" style="border:1px solid #333;"></canvas>

<script>
var c = document.getElementById("colorStops");
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(50, 50, 100, 100); 
</script>

</body>
</html>

Output:


Enjoy coding!