The Canvas element allows you to use a gradient as a background. This is done using a CanvasGradient object , which can be created either with the createLinearGradient() method (linear gradient) or with the createRadialGradient() method (radial gradient).
Linear Gradient
A linear gradient is created using the method createLinearGradient(x0, y0, x1, y1), where x0and y0are the start coordinates of the gradient, relative to the upper left corner of the canvas, and x1and y1are the coordinates of the end point of the gradient. For example:
var gradient = context.createLinearGradient(50, 30, 150, 150);
Also, to create a gradient, you must set the anchor points that determine the color. To do this, the CanvasGradient object uses the addColorStop(offset, color) method , where offset is the offset of the gradient point, and color is its color. For example:
gradient.addColorStop(0, "blue");
An offset represents a value between 0 and 1. An offset of 0 represents the beginning of the gradient, and 1 represents the end of the gradient. The color is specified either as a string, as a hexadecimal value, or as an rgb/rgba value.
Let’s apply a gradient:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas in HTML5</title> </head> <body> <canvas id="myCanvas" width="300" height="200" style="background-color:#eee; border:1px solid #ccc;"> Your browser does not support Canvas </canvas> </body> </html>
In this case, we get a diagonal linear gradient. By manipulating the coordinates, we can achieve a horizontal or vertical gradient.
Matching the x-coordinates of the start and end points creates a horizontal gradient:
gradient = context.createLinearGradient(50, 30, 50, 150);
And the coincidence of the y-coordinates of the start and end points creates a horizontal gradient:
gradient = context.createLinearGradient(50, 30, 150, 30);
Radial Gradient
The radial gradient is created using the method createRadialGradient(x0, y0, r0, x1, y1, r1), which takes the following parameters:
- x0 and y0: coordinates of the center of the first circle
- r0: radius of the first circle
- x1 and y1: coordinates of the center of the second circle
- r1: radius of the second circle
For example:
var gradient = context.createRadialGradient(120,100,100,120,100,30);
And also for the radial gradient, we need to set the anchor color points using the methodaddColorStop()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas in HTML5</title> </head> <body> <canvas id="myCanvas" width="300" height="200" style="background-color:#eee; border:1px solid #ccc;"> Your browser does not support Canvas </canvas> </body> </html>