createLinearGradient() and createRadialGradient() (Canvas)

createLinearGradient()

The createLinearGradient() method is used to return a gradient object that represents a linear gradient for painting a specified color along a line.

The following syntax can be used to apply a linear gradient:

createLinearGradient(x0,y0,x1,y1);

In the preceding syntax:

  • x0: Specifies the x-cooridinate of the starting point of the gradient.
  • y0: Specifies the y-cooridinate of the starting point of the gradient.
  • x1: Specifies the x-cooridinate of the end point of the gradient.
  • y1: Specifies the y-cooridinate of the end point of the gradient.
After creating the linear gradient object, you need to create the gradients by using the addColorStop() method.

Consider the following code for applying a linear gradient on a rectangle:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black">
</CANVAS>
<SCRIPT>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grad=ctx.createLinearGradient(0,0,170,0);
grad.addColorStop(0,"pink");
grad.addColorStop(0.5,"red");
grad.addColorStop(1,"yellow");
ctx.fillStyle=grad;
ctx.fillRect(20,20,180,180);
</SCRIPT>
</BODY>
</HTML>

Result:

createRadialGradient()

The createRadialGradient() method is used to return a gradient object that represents a radial or a circular gradient to be applied on a graphic object.
A circular gradient paints colors along a cone specified by two circles inner and outer.


The following syntax can be used to apply a radial gradient:

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

In the preceding syntax:


  • x0: Specifies the x-cooridinate of the starting point of the gradient.
  • y0: Specifies the y-cooridinate of the starting point of the gradient.(x0,y0) specifies the center coordinate of the first circle of the cone.
  • r0: Specifies the radius of the starting circle.
  • x1: Specifies the x-cooridinate of the end point of the gradient.
  • y1: Specifies the y-cooridinate of the end point of the gradient.(x1,y1) specifies the center coordinate of the second circle of the cone.
  • r1: Specifies the radius of the ending circle.



<!DOCTYPE HTML>
<HTML>
<BODY>
<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black">
</CANVAS>
<SCRIPT>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grad=ctx.createRadialGradient(75,50,5,90,60,100);
grad.addColorStop(0,"pink");
grad.addColorStop(0.5,"red");
grad.addColorStop(1,"yellow");
ctx.fillStyle=grad;
ctx.fillRect(20,20,180,180);
</SCRIPT>
</BODY>
</HTML>


Result:







About Codingwelove

Codingwelove
Recommended Posts × +

0 comments:

Post a Comment