Read my book

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

Wednesday, August 4, 2010

HTML5 Canvas Gradients - Triangle Gradient

This time I'm going to show you how to render a gradient using triangle vertex colors. In case you have played around with OpenGL, DirectX or some 3D graphics application you might be familiar with the expected result already.

Before delving into the code I will explain the math behind the approach chosen.


I have tried to characterize the basic approach in the image below:
Each vertex of the triangle is characterized by its location (x, y) and color. In order to figure out the interpolation factor for each vertex of the triangle I decided to use formula "1 - distance(point, vertex) - distance(intersection, vertex)". This means that the closer the current point is to the vertex, the bigger its contribution to the end result. I perform this check multiplied with vertex color for each vertex and sum the result.

Triangle Gradient

Here's my implementation of the idea:

You can find the files the example depends upon here.

The idea transformed to actual code quite well. There are a couple of boundary cases that needs to be taken care of but nothing too serious. I decided to form my Triangle structure so that the index of each edge corresponds to the index of vertex opposite to it. This makes it easy to handle the intersection check.

Here's a sample render of the expected result:
As can be seen there's still quite a bit of aliasing going on. I won't worry about that in this post, though. I am going to leave that as an exercise for the reader to solve. Hints: look out sampling, try sampling only around the edges for better performance.


In this part of the series I showed you how to render a simple triangle gradient using HTML5 Canvas element. It's a bit crude but does the job.

The basic idea makes it possible to mimic other gradients such as radial gradient discussed before. All you need to do is to come up with the right vertex structure.