How to change colors with a smoothly effect  

  Haxe  tutorial   Dec 13, 2014

For the last Ludum Dare, I wanted to have a nice effect on the background of my puzzle game in order to change the color based on the action on the board.

My game is in JavaScript, but except the background property, it should work on other platform too.

So, what do we need ?

First we have to get the initial color (color1) and the new one (color2). In order to change the color smoothly, we will do it with a Timer object.

// définition de la classe	
function changeColor(pElem: js.html.Element, pInitialColor: RGB, pEndColor: RGB){}

Here is the RGB typedef:

typedef RGB = {
	var r : Int;
	var g : Int;
	var b : Int;

The first step is the calculate the distance between those two colors (all methods are based on the RGB type):

var distance = {
	r: Math.round(Math.abs(color1.r - color2.r)),
	g: Math.round(Math.abs(color1.g - color2.g)),
	b: Math.round(Math.abs(color1.b - color2.b))

Now that we have the difference, we have to calculate the value that will determine how the color will change between each step:

var incR = Math.abs( Math.floor(distance.r / INCREMENT_VALUE) ) );
var incG = Math.abs( Math.floor(distance.g / INCREMENT_VALUE) ) );
var incB = Math.abs( Math.floor(distance.b / INCREMENT_VALUE) ) );

var increment = {
	r: incR == 0 ? 1 : incR,
	g: incG == 0 ? 1 : incG,
	b: incB == 0 ? 1 : incB

The INCREMENT_VALUE value allows use to determine how we want the effect to change. The higher the value is, the quicker the effect will be.

I've set it to 100.

Now we have to calculate the new color :

if (color1.r > color2.r) 
	color1.r -= increment.r;
	if (color1.r <= color2.r) // if we've reach the right color
		increment.r = 0;		
	color1.r += increment.r;
	if (color1.r >= color2.r) // if we've reach the right color
		increment.r = 0;

And same thing for each tone.

I'll now add this step to the Timer object.

I'm using the Timer class in order to have a cross platform method. But you can use any kind of listener or Signal.

var timer = new haxe.Timer(Math.round(1000 / (INCREMENT_VALUE/2))) = function()
	// [...] 

In this loop, you'll have to change the property of your object.

For example in JavaScript you'll have : = rgb2hex(currentColor);

Where rgb2hex transform the RGB object in hexa :

private static function rgb2hex(color: RGB): String
	return "#" + StringTools.hex(color.r, 2) + StringTools.hex(color.g, 2) + StringTools.hex(color.b, 2);

Here is an example :

Share it