Before delving into the code I will explain the math behind the approach chosen.
MathI have tried to characterize the basic approach in the image below:
Triangle GradientHere'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:
ConclusionIn 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.