2

Let me start by saying I have scoured the internet all day looking for a solution, and I'm just stumped. I managed to find enough code snippets to put together an "almost" working version of what I need -- but to be completely honest I'm just lost when it comes to how to make it work.

Here's what I'm trying to do:

I'm trying to make a php function that will take 2 or maybe 3 colors, and apply them as a smooth gradient to a text string. I need the function to output the actual HTML code for the gradient. How I envision it working is: it will take the message string and split it into the individual characters, and then color each character in such a way that when it's displayed with the html output, it will look like a smooth fade from one color to the next. Right now I'm testing the function with 2 colors that I've just defined inside it, (FF0000 and 0000FF). I can't seem to get it to color the entire string. It seems to grab the first letter, and do part of the transition, and then just stop.

Here's a screenshot of what I'm trying to make it look like: enter image description here

Here's a screenshot of what mine comes out looking like (including the html output for explanation sake) enter image description here

Here's the code that I'm using:

<?php 
function html2rgb($color)
{
    if ($color[0] == '#')
        $color = substr($color, 1);

    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0].$color[1],
                                 $color[2].$color[3],
                                 $color[4].$color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return false;

    $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

    return array($r, $g, $b);
}
function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}
    echo "<h1>Result:</h1>";
    $src_color = html2rgb('FF0000');
    $dst_color = html2rgb('0000FF');
    print_r($dst_color);

    for($i=0; $i<3; $i++)
        $step_color[$i] = ( $dst_color[$i] - $src_color[$i] ) / 30.30;
    // step_color array contains difference between adjacent color stripes

    $html_out = ''; // html code container

    for($j=0; $j<60; $j++)
    {
    // generate color stripe code

        $message = 'I am trying to make this text string fade from one color to another';
        $counter = strlen($message);
        $array = str_split($message);
        $mycount = 0;


        if($mycount < $counter){
            $line = '<b><font color=" '.rgb2html($src_color).';">'.$array[$mycount].'</font></b>';
        $html_out .= "{$line}"; // save color stripe to display HTML code later
        $mycount = $mycount + 1;
        }
        echo $line; // output color stripe to browser

        for($i=0; $i<1; $i++) // incrementing each color component
            $src_color[$i] += $step_color[$i];
    }

?>
<h1>HTML Code:</h1>
<pre><?php
// output HTML code replacing < and > with &lt; and &gt;
$stuff = strtr($html_out, array('&' => '&amp;',
                            '<' => '&lt;',
                            '>'=> '&gt;'));
echo $stuff;

I'm fairly new to this sort of thing, so please don't be too brutal on me if my code is "arse-backwards" or poor. Can anyone point me in the right direction? I'm just at a loss for how to get it to do what I want it to do.

Thank you very much for taking the time to read this, and for any advice you can offer!

Edit: image link for bottom screenshot to make it easier to see https://i.stack.imgur.com/vsfdQ.jpg

UPDATE -- Ok, I've re-written most of the function and I almost have it working. The issue that I'm having now is that it's repeating the entire string over and over. It is applying the fade, but not the way it's supposed to. I need it to fade from one color to the next across the string. Here is a new screenshot of what it's doing now: enter image description here Here's the link for that so you can see it easier: https://i.stack.imgur.com/X0Pmq.jpg

Here's the new code that I'm using:

<?php
function rgb($rgb) {
    $ret = '';
    foreach ($rgb as $x) {
        // Make sure the RGB values are 0-255...
        $x = max(0, min(255, $x));
        // create a 2 digit hex value for this color component...
        $ret .= ($x < 16 ? '0'.dechex($x) : dechex($x));
    }
    return '#'.$ret;
}

// Returns a fade of $from into $to by $amount ($from and $to are RGB arrays)...
function fade($from, $to, $amount) {
    $rgb = array();
    // Go through the RGB values and adjust the values by $amount...
    for ($i = 0; $i <= 2; $i++) {
        $rgb[$i] = (($to[$i] - $from[$i]) * $amount) + $from[$i];
    }
    return $rgb;
}
$string = 'testing out the fade function here';
//$string1 = strlen($string);
for ($j = 0; $j < 1; $j += .01) {
    $color = rgb(fade(array(255,0,0), array(0,255,0), $j));

    for($i=0;$i<strlen($string);$i++){
echo "<font style='color:$color'>$string[$i]</font>";
}

}

Is anyone able to tell me how to make it print the string just ONCE, with the fade properly applied to the string?

Thank you all so much for all of your time and expertise!

Mike Roberts
  • 161
  • 2
  • 14
  • Perhaps http://stackoverflow.com/questions/5634471/can-i-have-a-horizontal-multiple-colour-gradient-on-text-using-css3-html-5 – mplungjan Apr 24 '15 at 06:00
  • Please see my edit. At first it was coloring the entire line. now it applies only to the text – 1'' Apr 24 '15 at 06:12

2 Answers2

2

Check second example as it is more of what you're looking for.

Just use php to add the html elements and their ids or classes and then use css to give the gradient.

Example:

#id_of_element {      /*or class of element*/
    background: -webkit-linear-gradient(left, red , blue);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;

    /* the following would cover other browsers...not sure about IE */
    background: -webkit-linear-gradient(left, red , blue); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, red, blue); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, red, blue); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, red , blue); /* Standard syntax */
    /* then just add the -o- or -moz- etc. */
}

Depending on which angle or direction you want to gradient to go -> just use php (and/or javascript) to alter the value of the background: -webkit-linear-gradient(direction, color1 , color2);

THE FOLLOWING IS THE CODE EXAMPLE

Try the code below as an example:

Afterwards, open the page up in a web browser. It should have text that goes from black to white.

After APPEND this to the url:

?color1=FFFFFF&color2=000000

So the full url should look something like this:

http://yoursite.com/pageName.php?color1=FFFFFF&color2=000000

Now the gradient is reversed. because color1 originally started out as #000000 but the php switched it because of the value it had from the GET request.

Here is the code example:

<?php 
    $textOutput = '';
?>
<?php if(isset($_GET['color1']) && isset($_GET['color2'])):
    $textOutput = '';
    $userFirstInput  = $_GET['color1'];  // these are the posts or gets you send from your form
    $userSecondInput = $_GET['color2']; // these are the posts or gets you send from your form

    $firstColor = $userFirstInput;    // #FFFFFF for example
    $secondColor = $userSecondInput;  // #000000 for example

    $textOutput .= '.spans{';
    $textOutput .= 'background: -webkit-linear-gradient(left, #'. $firstColor . ', #'.$secondColor .');';
    $textOutput .= '-webkit-background-clip: text;';
    $textOutput .= '-webkit-text-fill-color: transparent;';
?>
<?php else:
    $textOutput = '';
    $textOutput .= '.spans{';
    $textOutput .= 'background: -webkit-linear-gradient(left, #000000 , #FFFFFF);';
    $textOutput .= '-webkit-background-clip: text;';
    $textOutput .= '-webkit-text-fill-color: transparent;';
?>
<?php endif ?>
<!DOCTYPE html>
<html>
<head>
<style>
    <?php echo $textOutput; ?>
</style>
<span class="spans">IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII</span>
</body>
</html>

If you need help getting the user input, that I can help with as well. I use ajax to send a post or get up to PHP and check/sanitize the inputs.

1''
  • 324
  • 1
  • 10
  • I appreciate you taking the time to answer! I did see this method used on other sites, but the problem I have is that I need it to output the actual HTML code (as seen in the screenshot above). I was headed in the right direction I think, I've just got some bugs in my code that are preventing it from stretching the gradient across the whole string ** EDITED** to be more transparent -- I'm using the function on a chat website. We are trying to allow chatters to use a /fade command to create a faded text message on the main screen -- which is why I need it to output the actual markup – Mike Roberts Apr 24 '15 at 12:53
  • @MikeRoberts Any function can output the actual markup. Just set the html equal to some variable and append the element with styles to it (the variable) and append the closing html tags to it once again. Then echo the variable out. out. – 1'' Apr 24 '15 at 23:49
  • @user3473227 -- Ok that makes sense logically, and I appreciate your information! Would you be able to give me any sort of example at all so I know where to start? Thank you again for so much of your time – Mike Roberts Apr 25 '15 at 01:50
  • @MikeRoberts BTW you can change the colors to red and blue. I used black and white for no special reason. – 1'' Apr 25 '15 at 02:36
  • @user3473227 Thank you for taking the time to make that example! I was able to get it to work the way I wanted it to for chrome, but the gradients don't show up in IE. I'm guessing that has something to do with the webkit stuff? Is there a way to make them show up cross browser? – Mike Roberts Apr 25 '15 at 15:41
  • Update - Ok, so I was able to get "most" of it working cross browser, but the snag I'm hitting is that the background-clip:text doesn't seem to work in IE. Is there an alternative syntax for ie? I've been googling but coming up short here – Mike Roberts Apr 25 '15 at 16:18
  • @MikeRoberts did you try `-ms-background-clip:text` – 1'' Apr 26 '15 at 02:43
  • I've read that IE7 had support for it, that some are getting the desired results but perhaps not with a gradient. I'm sure there is a way to hack it out. I'll continue checking back to see if it works for you. – 1'' Apr 26 '15 at 02:45
  • I tried it, but it doesn't seem to work in ie10. For now I've just given up and set the fade using a manual array of colors and not allowed the user to specify the colors. I did add a section to my original question with a different method, it was close, but not quite working -- if that makes any difference? – Mike Roberts Apr 26 '15 at 03:34
0

Why don't do like that

$string = 'My text'
$count = 0;
for($i=0,$i<=255,$i++){
   for($i_i=0,$i_i<=255,$i_i++){
      for($i_i_i=0,$i_i_i<=255,$i_i_i++){
            echo '<span style="color:rgb('.$i.','.$i_i.','.$i_i_i.')">'.$string[$count].'</span>';
            if($count == strlen($string))break;
            $count++;
      }
      if($count == strlen($string))break;
   }
   if($count == strlen($string))break;
}

Or set some other values of $i... to get another colors.

winston86
  • 159
  • 1
  • 8
  • Also you can change `$i, $i_i, $i_i_i` in `echo` function. – winston86 Apr 24 '15 at 06:09
  • Thank you for taking the time to write up an answer. I'm trying to sort out how I would incorporate the code you wrote into my sample to make it work. I'll keep at it here. This whole function just has me baffled. lol – Mike Roberts Apr 24 '15 at 13:50
  • I modified my code and updated the original question. Is this any closer to what you were talking about? – Mike Roberts Apr 25 '15 at 18:21
  • Try to build `$i` (`for($i,$i<255,$i=$i + your iterator)`) depend on lenght of your string. – winston86 Apr 29 '15 at 04:18