Read my book

I wrote books about Webpack and React. Check them out!

Thursday, August 25, 2011

HTML5 Canvas Gradients - Rectangular Gradient

I came by an interesting question at Stack Overflow a while ago. It asked how to render a rectangular gradient using HTML5 Canvas. I'm going to present you my solution in this post. It ended up being quite nice and simple.


The solution is visible below:

As you can see it is just a matter of doing two things. First you have to render a linear gradient on the background. After that you have to finish it up by rendering another linear gradient (opposite direction!) while clipping it with a bow tie shape. That's it!

Note that it's a good idea to restore the context after doing some clipping on it. You often don't want to perform the same clip on the later operations.