html5 canvas circle with gradient fill example


A friend asked me a question on how to do a gradient circle in HTML5 canvas. To be honest I never used gradients before so it was fun to find it how to do it. It was easy and didn’t take me to long that functions such as

  1. createLinerGradient()
  2. createRadialGradient()

exists in canvas context API to make use of

So lets go ahead and check out how this is done

Normal steps include to mention the markup first

The Markup

So we just created a 500×500 canvas now lets jump into our JavaScript section to see how we can draw a circle.


The Javascript

Above code will give us a circle as shown below

html4 canvas circle

But thats not gradient you will say right, because we have drawn it yet. so lets draw a radial gradient circle

A radial gradient circle in html5 canvas

As you can see that we are making use of function createRadialGradient(). Here is definition of this function

The Result

html5 canvas radial circle example



Lets use the same technique to create a Linear gradient circle. Code is given below

HTML5 canvas circle with Linear gradient

The Result

The result will look like this

html5 circle linear gradient example

Here is details of params accepted by  createLinearGradient() function

I hope that this helps.

If you think there is some error or code can be improved please leave your comments. I appreciate every ounce of feedback. You can try various things by making small changes to the supplied code to get your understanding on Gradients more firm.





Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.