a blog for those who code

Thursday 22 October 2015

How to create Linear and Radial gradients in HTML5

In this post we will be discussing about Linear and Radial gradients in HTML5 using <canvas> element. Linear gradient can be seen as a rectangle where a set of colors are interpolated along a line whereas in Radial gradient colors are interpolated along circles.The gradient becomes visible when we draw shapes on top of the "invisible gradient" created by canvas. If you are not familiar with <canvas> element in HTML5, you can start with Beginning with Canvas element in HTML5.


Creating Linear Gradient

For creating linear gradient using canvas element at first we need to define a linear gradient as shown below where (x0, y0) and (x1, y1) defines the direction of the gradient. For example, (0,0) and (200,0) will create lines (invisible lines) from top left corner of the canvas (0,0) to the top right corner of the canvas (200,0).

var linearGradient = context.createLinearGradient(x0, y0, x1, y1);

After defining the gradient we need add colors to the gradient. Colors should have stops which will go from 0 to 1 as shown below.

linearGradient.addColorStop(0, "red");
linearGradient.addColorStop(0.5, "blue");
linearGradient.addColorStop(1, "green");

And then we will draw rectangle after setting fillStyle of the context with the the linear gradient we have created above as shown below.

context.fillStyle = linearGradient;
context.fillRect(0, 0, 300, 200);

Result : http://codepen.io/codingdefined/pen/KdQaXE


Creating Radial Gradient

For creating radial gradient using canvas element at first we need to define a radial gradient as shown below where (x1, y1) and (x2, y2) defines the center of the smaller circle (radius1) and larger circle (radius2).

var radialGradient = context.createRadialGradient(x1, y1, radius1, x2, y2, radius2);

After defining the gradient we need add colors to the gradient. Colors should have stops which will go from 0 to 1 as shown below.

radialGradient.addColorStop(0, "red");
radialGradient.addColorStop(0.5, "blue");
radialGradient.addColorStop(1, "green");

And then we will draw rectangle after setting fillStyle of the context with the the radial gradient we have created above as shown below.

context.fillStyle = radialGradient;
context.fillRect(0, 0, 300, 200);

Result : http://codepen.io/codingdefined/pen/dYdNeR


Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

No comments:

Post a Comment