Tutorials

KodeKite Tools

HTML
Flexbox
SVG
Canvas
More


Canvas Linear-Gradient
Canvas Linear-Gradient

LinearGradient is used to creates linear pattern in three ways such as horizontal, vertical and diagonal. createLinearGradient() method is used to create linear gradient object by using co-ordinates (x1,y1,x2,y2), where x1 and y1 are the intial points and x2 and y2 are the final points. The points x1 and x2 can be used to create horizontal gradient and the points y1 and y2 can be used to create vertical gradient and both points can be used to create diagonal gradient.

addColorStop(position,color)

addcolorStop method is used create a new color stop on the gradient objectcreated by createLinearGradient method. The parameter position in addColorStop method is a number between 0.0 to 1.0 and defines the relative position of color in a gradient and color is css color values, multiple color stops can be added in gradient.

Syntax

var variableName = canvas.getContext(2d);
variableName.createLinearGradient(x1,x2,y1,y2);


Example


You can apply any number of colors to linear Gradient.


Practice Task

Open notepad or any other text editor, follow the following points.


  • Use <canvas> element to draw canvas on webpage
  • Assign id <linearG> to canvas element
  • Give width and height of 250 250 respectivelly
  • Use inline style to style canvas element
  • Give border and to canvas using css styles
  • Border should be 3px solid green
  • Use javascript to draw linear gradient on canvas, apply any number of colors

save file with name task.html or task.htm and then open it using any browser and see results.


Solution