html tutorial - createLinearGradient Method in HTML5 Canvas - html5 - html code - html form
Learn html - html tutorial - Createlineargradient method in html5 canvas - html examples - html programs
- The createLinearGradient() method is used to create a linear gradient object in HTML Canvas.
- This object is used to fill the different colors in a drawing.
- It has four parameters they are x0, y0, x1 and y1.
Syntax for createLinearGradient() method in HTML5 Canvas:
Parameter values:
parameter | Description |
---|---|
X0 | This is a starting point of an x axis coordinate of the gradient. |
Y0 | This is a starting point of a y axis coordinate of the gradient. |
X1 | This is an ending point of an x axis coordinate of the gradient. |
Y1 | This is an ending point of a y axis coordinate of the gradient. |
Sample coding for createLinearGradient() method in HTML5 Canvas:
Code Explanation for createLinearGradient() method in HTML5 Canvas:
- ”wikitechyCanvas” is used to define the value of id attribute for canvas element
- The getElementById(); method is used to get the element that has the id attributes with the specified value.
- a.getContext(“2d”) method is returns a two-dimensional drawing context on the canvas.
- The clg is created using a createLinearGradient() method which is set the position of the gradient.
- clg.addColorStop(0,”yellow”) is used to specify the color of a gradient as well as its stop to fill the color when its reach the gradient specific position.
- The clg.addColorStop(1,”pink”) is start to fill pink color to a rectangle when the yellow color reached the specific position of the gradient.
- fillStyle property is used to fill linear gradient to the rectangle on the canvas.
- fillRect() method is used to draw a filled rectangle on the canvas.
Sample Output for createLinearGradient() method in HTML5 Canvas:
The output shows that the linear gradient goes from yellow to pink, as the fill style for the rectangle.
- The canvas rectangle with blue border.
- The linear gradient start to fill yellow color from the left side to specified gradient position.
- The linear gradient start to fill the pink color from the specific gradient position to right side of a rectangle.
Browser Support for createLinearGradient():
Yes | Yes | Yes | Yes | Yes |
Tips and Notes
- Use createLinearGradient() object as the value to the strokeStyle or fillStyle properties.
- The addColorStop() method is used to specify different color of the gradient object and where to the position the colors in the gradient.