How to use gradient in HTML Canvas?

Gradients are used to perform smooth colour transitions using two or more colours. In Canvas we can use two types of gradients: linear and radial.

Linear Gradient

createLinearGradient(x,y,x1,y1) creates linear gradient in Canvas that paints along the line represented in the arguments. In addition we have to specify two colour stops using  addColorStop() ,which specifies the colour and its position along the gradient. To use the gradient, we have to set the  fillStyle  or  strokeStyle  property to gradient and draw the canvas.

Radial Gradient

createRadialGradient(x,y,r,x1,y1,r1)  creates radial gradient in Canvas that paints along the cone represented by circles in the arguments.

HTML

 

JS 

Output

Radial Gradient in Canvas

Linear Gradient in Canvas

Leave a Reply