Fade Colors on a Polygon using the Game Loop

Posted by in Software, Tutorial

One of the features I need to implement is to smoothly change the fill/stroke color of a polygon, like this:

A manual approach

In order to better understand the mechanics, I built my own fading PoC.

First, one would need to build the polygon:

In this particular case, I have a text field and a rounded rectangle beneath it. the hud group contains both in the right order.

Once the components have been created, we build the function to be called each frame:

The idea is to only perform the loop once, for the first 100 frames. As you can see, the dt velue does not yet enter into play so, the dransition from black to red is not perfectly smooth.

Now, all we need to do is to register the function with the frame event:

Once we do this, the rectangle fades from black to red in 100 frames. At 60fps, this would mean approximately 1.5 seconds.

Constant speed

As mentioned above, the speed of changing the colors is not constant. If e.g. we have a longer delay between frames, there’s going to be jitter and the time in which we’ll make the transition will vary. To improve this, we put dt in play:

This is a bit verbose, but following components can be identified easily:

  1. .duration field which represents the duration in seconds at 60fps
  2. .progress the decreasing value. It will decrease with dt each frame
  3. curtime and .lastTime are used to compute the dt (delta) between frames
  4. if (self.duration ...) block performing:
    • .progress update
    • activation logic
    • the actuall logic (changing the fill colour)

As mentioned above, this variant provides a constant speed of change and better control.

Its downside is the estra values and adding the logic of converting the dt into something meaningful.


A little experiment: If you find this post and ad below useful, please check the ad out :-)