How to Create Gradient in HTML5


Gradient in Html5 is used to fill shapes and text with multiple colors instead of a single one. In a gradient, the color flows from one color to another. There are two types of gradient based on the flow of the color, namely linear and radial gradients. So in this tutorial we will work on html5 gradients.

Step # 1 – Open IDE

Now, to begin, first you will have to open an IDE, let’s say Dreamweaver. Now, from its menu, choose HTML from Create New.

Create New “HTML” option

Step # 2 – Basic Code

Now, for the main code, a basic canvas can be made through this code.

Basic Canvas Code

Step # 3 – Linear Gradient

First, we will start with the linear gradient.

The getElementById function is used to identify our canvas,

The getContent(“2d”) object, which is a built-in HTML5 object, helps in working on the canvas.

The next function, createLinearGradient is used to point x and y position of the first and second color.

The function addColorStop is used to provide the canvas with the first and second color of the gradient. Right after that, the type of fill, which is a gradient in this case, and its shape on the canvas, which in this example is done by the functions fillStyle and fillRect, respectively.

Linear Gradient

Step # 4 – Radial Gradient

The other type of gradient, i.e. the radial gradient, is implemented in the same manner, just replacing the createLinearGradient function with createRadialGradient, in which we have to provide the x, y position as well as the radius of both the colors.

Radial Gradient

And this was all about html5 gradients.