I have some IDs that I want to generate random colours for. Making random colours is not the issue, but it has to be consistent.
I could MD5 (or some other kind of hash) the IDs so the code could know how much characters to expect, but the bottomline is it has to generate the same (random) colour for the same ID/hash/string.
There is no way to do this using CSS only. CSS doesn't support logical statements because CSS is purely deterministic (there is nothing like array etc in CSS). We can use client-side JavaScript to select a random color from the array.
All you need for a RGB code is a consistent mapping from your random string to a 6 position hex value. Why not use md5 as a way to a hex string, and then take the first 6 digits?
<?php
function rgbcode($id){
return '#'.substr(md5($id), 0, 6);
}
?>
Here's a simple function that I'm using in one of my own projects to create RGB values which I can use with PHP's imagecolorallocatealpha
:
function randomRgbGeneratorFromId( $id = null ) {
$md5 = md5( $id );
$md5 = preg_replace( '/[^0-9a-fA-F]/', '', $md5 );
$color = substr( $md5, 0, 6 );
$hex = str_split( $color, 1 );
$rgbd = array_map( 'hexdec', $hex );
$rgba = array(
( $rgbd[0] * $rgbd[1] ),
( $rgbd[2] * $rgbd[3] ),
( $rgbd[4] * $rgbd[5] ),
);
return $rgba;
}
Of course you can always output to your CSS / HTML by using something like this:
echo sprintf( 'rgb(%s)', implode( ',', randomRgbGeneratorFromId( $id ) ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With