Creating a Strobe Light Generator

by kirupa   |   27 May 2013

Yes, I may have mentioned many times that animations should be tasteful, subtle, and help enhance your content. Not everything has to be like that, though. Sometimes, it is just fun to let your animations go a little crazy. This is especially true if your animation needs to be the center of attention.

One example of such an animation is what you will see when you click on the go link below:

What you are seeing is an effect where the background color is changing really quickly from one random color to another. If staring at the rapidly flashing colors gets too annoying for you, reload this page to reset this example back to the go page. Just don't click on the go link again :P

In this short deconstruction, you will learn how to create this effect - an effect better known as the strobe light generator. Besides creating something that will annoy everybody around you when played on a large screen (direct link to example), you'll see me employ some interesting tricks around how to generate random colors and throttle the speed at which requestAnimationFrame runs. There is something interesting for everybody here!

Onwards!

The Code

The full HTML, CSS, and JavaScript that makes up this example looks as follows:

<!DOCTYPE html>
<html>
 
<head>
<meta charset="utf-8">
<meta content="Strobe Light Generator" name="title">
<title>Strobe Light Generator</title>
</head>
 
<body>

 
<script>

var bodyElement = document.querySelector("body");

var requestAnimationFrame = window.requestAnimationFrame || 
                            window.mozRequestAnimationFrame || 
                            window.webkitRequestAnimationFrame || 
                            window.msRequestAnimationFrame;

var delay = 0;

function changeColor() {
	delay++;
	
	if (delay > 3) {
		bodyElement.style.backgroundColor = getRandomColor();
		delay = 0;
	}

    requestAnimationFrame(changeColor);
}
changeColor();           

function getRandomColor() {
	// creating a random number between 0 and 255
	var r = Math.floor(Math.random()*256);
	var g = Math.floor(Math.random()*256);
	var b = Math.floor(Math.random()*256);
	
	// going from decimal to hex
	var hexR = r.toString(16);
	var hexG = g.toString(16);
	var hexB = b.toString(16);
	
	// making sure single character values are prepended with a "0"
	if (hexR.length == 1) {
		hexR = "0" + hexR;
	}
	
	if (hexG.length == 1) {
		hexG = "0" + hexG;
	}

	if (hexB.length == 1) {
		hexB = "0" + hexB;
	}

	// creating the hex value by concatenatening the string values
	var hexColor = "#" + hexR + hexG + hexB;
	return hexColor.toUpperCase();
}
</script>
</body>
</html>

As you can tell, this example is almost entirely made up of JavaScript. You have no CSS and nothing beyond the bare minimum HTML needed to create an HTML5 document. With that initial observation out of the way, take a few moments and look through the code. If you are familiar with the Animating with requestAnimationFrame and Random Colors in JavaScript tutorials, most of what you see should look familiar.

Once you've taken a few moments to look through the code, let's look at the interesting parts together.

The Deconstruction

The way our strobe light generator works is pretty straightforward. We have our requestAnimationFrame function that that calls the changeColor function sixty times a second:

var delay = 0;

function changeColor() {
	delay++;
	
	if (delay > 3) {
		bodyElement.style.backgroundColor = getRandomColor();
		delay = 0;
	}

    requestAnimationFrame(changeColor);
}
changeColor();  

The changeColor function is responsible for only one thing, and that thing is setting the background color on the body element to a random color:

var delay = 0;

function changeColor() {
	delay++;
	
	if (delay > 3) {
		bodyElement.style.backgroundColor = getRandomColor();
		delay = 0;
	}

    requestAnimationFrame(changeColor);
}
changeColor();  

All of the extra code you see around it is to ensure we don't actually change the color sixty times a second, but instead change the color at a slightly slower rate. Remember, there is no way to tell requestAnimationFrame to slow down. Instead, what you can do is ignore a few of the requestAnimationFrame calls and react at a slower rate.

The code you see highlighted does just that:

var delay = 0;

function changeColor() {
	delay++;
	
	if (delay > 3) {
		bodyElement.style.backgroundColor = getRandomColor();
		delay = 0;
	}

    requestAnimationFrame(changeColor);
}
changeColor();  

Our delay variable lives up to its name by delaying when your background color on body changes. When the delay variable's value exceeds 3, the if statement containing the code to change the background color executes. If the delay variable's value is less than 3, nothing happens. The code inside the if statement simply never gets hit.

Stepping back a bit, these five lines of code ensure that we change the color only once for every three times the requestAnimationFrame function calls the changeColor function. Another way of saying this is that we change the color twenty times a second. That's a much better pace for this effect. It is fast enough to be annoying but not too fast to a point where you can't really see every color.

The last thing to call out is the getRandomColor function that is responsible for returning a random hex value for color:

function getRandomColor() {
	// creating a random number between 0 and 255
	var r = Math.floor(Math.random()*256);
	var g = Math.floor(Math.random()*256);
	var b = Math.floor(Math.random()*256);
	
	// going from decimal to hex
	var hexR = r.toString(16);
	var hexG = g.toString(16);
	var hexB = b.toString(16);
	
	// making sure single character values are prepended with a "0"
	if (hexR.length == 1) {
		hexR = "0" + hexR;
	}
	
	if (hexG.length == 1) {
		hexG = "0" + hexG;
	}

	if (hexB.length == 1) {
		hexB = "0" + hexB;
	}

	// creating the hex value by concatenatening the string values
	var hexColor = "#" + hexR + hexG + hexB;
	return hexColor.toUpperCase();
}

What this function does and how it does it should be pretty self explanatory. If you want a detailed look into this function, do check out my Random Colors in JavaScript tutorial.

What You Learned

In this deconstruction, the main thing you learned is controlling how often your code executes when called by requestAnimationFrame. For most cases, you want your code to get called sixty times a second. In examples such as this where you want to slow things down a bit, you can do some variable trickery such as what we did with delay and "skip" a few requestAnimationFrame calls before executing your code.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!