Read my book

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

Tuesday, December 23, 2014

HTML5 Canvas Gradients - Rectangle Gradient with Arbitrary Corners

I recently found a question on how to generate a rectangle gradient with arbitrary corners on Stack Overflow. The problem is simple but there is no direct way to achieve this through the Canvas API.

Fortunately writing a generic solution is not that hard. I already did something like this in case of a triangle gradient. This is just a more specific problem. I've outlined the solution below.


Here is a simple demo for you to play with:

JS Bin

Code Example

And here is a full code example:

We just render a linear gradient per each line while interpolating the colors. Simple as that.

It would be possible to generalize this further to support more color stops etc. but I will leave that as an exercise for the reader.