February 5, 2010

AS3 RANDOM COLOR GENERATOR

[update]

A big thanks is owed to "rur" for pointing out an error in my code:
randNum = Math.round(Math.random() * 16);
should be:
randNum = Math.round(Math.random() * 15);
I owe you one!

[update 2]

As many people have pointed out, you can just use Math.random()*0xFFFFFF; or Math.round(Math.random()*0xFFFFFF);, but I'm not sure if you can get random colors within a range this easily (like getting only warm or only cool colors). If anyone can figure out how to do this, then this method is pretty much obsolete, and you should stop reading this.

Regardless, I've updated my example to include only warm colors within a range. I also took Dayvid Jones's excellent advice and am now generating the color in a public function instead of the constructor, which, because you only have to instantiate one object, is probably more efficient.

Explanation

Here’s my random color generator. I made it on a whim and haven't really used it on any projects, but hopefully someone can find it useful. It's pretty simple really. The hexadecimal system is base 16 as opposed to the base 10 system we're all used to, so 6 more digits are available.

Each hexadecimal color (html color) needs 6 digits. So, to get a random hex color, all you really need to do is radomly select one of the sixteen hexadecimal digits (0 - 9 and A - F) six times. For use in flash (and probably elsewhere) you need to add an extra "0x" before the actual random digits, so I you need to throw that onto the front.

Example Usage

Below is an example of how you can use the random number generator. I just threw it into a for loop, created a few of these cube-looking things (don't want it to be boring, right?), and voila! Pure awesomeness! Click the button and try to contain your excitement.

Here's the class I used. I didn't comment much, so post something or email me if you have a question.

package util
{
	
	public class RandomColor
	{
		private var randArray:Array = new Array();
		private var randChar:String;
		private var randNum:Number;
		private var color:uint;
		private var finalProduct:String;
		private var twoHexVals:String;
		
		public function RandomColor()
		{
			// left empty
		}
		
		public function getRandomColor(red:String = null, green:String = null, blue:String = null):uint
		{
			trace("Red: " + red + ", Green: " + green + ", Blue: " + blue);
			
			if(red == null)
				red = getRandomDigit();
			if(green == null)
				green = getRandomDigit();
			if(blue == null)
				blue = getRandomDigit();
			
			finalProduct = "0x" + red + green + blue;

			trace("Random Color: " + finalProduct);
			
			color = uint(finalProduct);
			
			return color;
		}
		
		function getRandomDigit():String
		{
			twoHexVals = new String();
			
			for(var j:int = 0; j < 2; j++)
			{
				randNum = Math.round(Math.random() * 15);
				
				if(randNum < 10)
					twoHexVals += String(randNum);
				else
				{
					switch(randNum)
					{
						case 10:
							randChar = 'A';
							break;
						case 11:
							randChar = 'B';
							break;
						case 12:
							randChar = 'C';
							break;
						case 13:
							randChar = 'D';
							break;
						case 14:
							randChar = 'E';
							break;
						case 15:
							randChar = 'F';
							break;
					}
					twoHexVals += String(randChar);
				}
			}
			
			return twoHexVals;
		}
		
	} //ends class
	
} //ends package

Here's what I have in my .fla file. It's just an example of how you can use the above class (and if anyone can't open a CS3 document, this is what's on my timeline)

import util.RandomColor;	// this is for the random color class (kept in classpath/util on my machine)

var rc:RandomColor = new RandomColor();
var col:uint;
var w:Number = 50;
var h:Number = 50;
var num:int = 100;
var numClicks:int = 0;

button.addEventListener(MouseEvent.CLICK, onClick);
button.buttonMode = true;
button.mouseChildren = false;

function onClick(e:MouseEvent):void
{
	clearStage()
	generateRandomColors();
}

generateRandomColors();

function generateRandomColors():void
{
	for(var j:int = 0; j < num; j++)
	{
		col = rc.getRandomColor("FF", null, "00");
		
		var sh:Shape = new Shape;
		sh.graphics.lineStyle(3, 0);
		sh.graphics.beginFill(col, 1);
		sh.graphics.moveTo(w/2, 0);
		sh.graphics.lineTo(w, h/3);
		sh.graphics.lineTo(w, 2*h/3);
		sh.graphics.lineTo(w/2, h);
		sh.graphics.lineTo(0, 2*h/3);
		sh.graphics.lineTo(0, h/3);
		sh.graphics.lineTo(w/2, 0);
	
		sh.graphics.endFill();
		sh.x = Math.random() * (stage.stageWidth - w);
		sh.y = Math.random() * (stage.stageHeight - h - 45);
		
		sh.alpha = sh.scaleY = sh.scaleX = Math.random();
		addChild(sh);
		
		setChildIndex(button, this.numChildren - 1);
	}
}


function clearStage():void
{
	while(this.numChildren > 1)
		removeChildAt(0);
}

download the .fla and the .as files.

Posted in actionscript

Comments:


hello world

jay | April 8, 2010 @ 12:08 pm

that should be:
randNum = Math.round(Math.random() * 15);
not:
randNum = Math.round(Math.random() * 16);

otherwise random char ends up as null when randNum is 16

rur | April 13, 2010 @ 10:16 am

or you could just use Math.random() * 0xFFFFF...

Mr. Second Opinion | August 12, 2010 @ 7:29 am

I changed it up a bit and added a param in the getColor method.  This param is a color that you don't want returned.  I used it for an object that I assigned a color to, while I had a bunch of other objects that I gave random colors too and didn't want them to share the color of the first object.

package
 { 
	public class RandomColor
	 { 	
		public function RandomColor()
		 { 
		 } 
		//
		public function getColor(aColor:uint = 0):uint
		 { 
			var color:uint = createColor();
			if (aColor != 0)
			 { 
				while(color == aColor)
				 { 
					color = createColor();
				 } 
			 } 
			return color;
		 } 
		//
		private function createColor():uint
		 { 
			var randArray:Array = new Array();
			var randChar:String;
			var randNum:Number;
			var finalProduct:String = "0x";
			//
			for(var j:int = 0; j < 6; j++)
			 { 
				randNum = Math.round(Math.random() * 15);
				if(randNum < 10)
					randArray.push(String(randNum));
				else
				 { 
					switch(randNum)
					 { 
						case 10:
							randChar = 'A';
							break;
						case 11:
							randChar = 'B';
							break;
						case 12:
							randChar = 'C';
							break;
						case 13:
							randChar = 'D';
							break;
						case 14:
							randChar = 'E';
							break;
						case 15:
							randChar = 'F';
							break;
					 } 
					randArray.push(randChar);
				 } 
			 } 
			
			for(var i:int = 0; i < 6; i++)
			 { 
				finalProduct += randArray[i];
			 } 
			
			return uint(finalProduct);
		 } 
		
	 } 
 } 

Dayvid Jones | November 20, 2010 @ 8:28 pm

A somewhat less complex way to do it is this;

Math.round( Math.random()*0xFFFFFF )

Bart Burkhardt | November 26, 2010 @ 3:11 am

Thanks, it help a lot!
Change the way the get a color, though. It become like Dayvid Jones did.

Mam | December 7, 2010 @ 12:56 pm

no, Math.round( Math.random()*0xFFFFFF ) its not the same noobs

Simon | April 13, 2011 @ 1:06 am

Nice update.  I merged it with mine, and made the methods static so you don't need to instiate the class.  And you can pass a vector (array) that holds colors you don't want returned.

package
 { 
	public class RandomColor
	 { 
		public function RandomColor()
		 { 
		 } 
		
		public static function getColor(red:String = null, green:String = null, blue:String = null, dontReturnColors:Vector.<uint> = null):uint
		 { 			
			var color:uint;
			
			if (dontReturnColors != null && dontReturnColors.length > 0)
			 { 
				var colorOkay:Boolean = false;
				
				while(!colorOkay)
				 { 
					color = getRandomColor(red, green, blue);
					
					colorOkay = true;
					
					for (var i:uint = 0; i < dontReturnColors.length; i++)
					 { 
						if (color == dontReturnColors[i])
						 { 
							colorOkay = false;
							break;
						 } 
					 } 
				 } 
			 } 
			else
			 { 
				color = getRandomColor(red, green, blue);
			 } 
			
			return color;
		 } 
		
		private static function getRandomColor(red:String = null, green:String = null, blue:String = null):uint
		 { 
			var color:uint;
			var finalProduct:String;
			
			if(red == null)
				red = getRandomDigit();
			if(green == null)
				green = getRandomDigit();
			if(blue == null)
				blue = getRandomDigit();
			
			finalProduct = "0x" + red + green + blue;
			
			color = uint(finalProduct);
			
			return color;
		 } 
		
		private static function getRandomDigit():String
		 { 
			var randChar:String;
			var randNum:Number;
			var twoHexVals:String;
			
			twoHexVals = new String();
			
			for(var j:int = 0; j < 2; j++)
			 { 
				randNum = Math.round(Math.random() * 15);
				
				if(randNum < 10)
					twoHexVals += String(randNum);
				else
				 { 
					switch(randNum)
					 { 
						case 10:
							randChar = 'A';
							break;
						case 11:
							randChar = 'B';
							break;
						case 12:
							randChar = 'C';
							break;
						case 13:
							randChar = 'D';
							break;
						case 14:
							randChar = 'E';
							break;
						case 15:
							randChar = 'F';
							break;
					 } 
					twoHexVals += String(randChar);
				 } 
			 } 
			
			return twoHexVals;
		 } 
	 } 
 } 

Dayvid Jones | April 14, 2011 @ 2:39 pm

Hey thanks for the color generator, thats good stuff!

Joe | June 5, 2011 @ 5:13 pm

Math.random()*0x888888  should do the trick for cold color

and Math.random()*0x555555 + 0xaaaaaa  for warm ones ;)

Masamune | July 26, 2011 @ 7:39 am

You can also favoritze some kind of color this way

Math.random()*0x00FFFF + 0xFF0000 (red always on max)

Hope it helps ;))

Cheers from France !

Masamune | July 26, 2011 @ 7:41 am

I like it!!  Just what I was looking for.  Adding a random color to the background of repeated items.

Thanks!

Dean | September 14, 2011 @ 12:58 pm

var o=new String;
arr=new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
var n1=Math.round(Math.random()*15);
var n2=Math.round(Math.random()*15);
var n3=Math.round(Math.random()*15);
var n4=Math.round(Math.random()*15);
var n5=Math.round(Math.random()*15);
var n6=Math.round(Math.random()*15);
 
o="."+arr[n1]+""+arr[n2]+""+arr[n3]+""+arr[n4]+""+arr[n5]+""+arr[n6];
document.write(o);
window.document.bgColor=o;


hi,Its my code i want show random color on id how to do?please help me

Nikhil | August 22, 2012 @ 4:25 am

What do you think?

(All fields required. Only your name and comment will be stored.)
Name:

Email:

Code:
validation image
Message: