Move text background

5

Personal I need to place and animate a degrade as background of a font with a written text.

I need this gradient to be applied at the font (not behind the text) and move from left to right indefinitely. How do I do this with CSS or JQuery?

The background has it in both image and CSS. CSS gradient:

background: #f44730; /* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2Y0NDczMCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjI2JSIgc3RvcC1jb2xvcj0iI2Y3ZjAyZSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUxJSIgc3RvcC1jb2xvcj0iIzJkYmExZCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9Ijc2JSIgc3RvcC1jb2xvcj0iIzIzNzVkYiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNkMTExMDAiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(left,  #f44730 0%, #f7f02e 26%, #2dba1d 51%, #2375db 76%, #d11100 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#f44730), color-stop(26%,#f7f02e), color-stop(51%,#2dba1d), color-stop(76%,#2375db), color-stop(100%,#d11100)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(left,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(left,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* IE10+ */
background: linear-gradient(to right,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f44730', endColorstr='#d11100',GradientType=1 ); /* IE6-8 */
    
asked by anonymous 14.04.2015 / 16:35

5 answers

6

In the absence of a response that reaches 100% AP problems, I risk publishing an alternative using SVG , which consists of the following (commented code explaining what each part is):

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%">

  <!-- Aqui você informa seu texto -->
  <!-- Também é possivel setar o tamanho da font do texto, com o atributo "font-size" -->
  <!-- Text utiliza o #pattern (que é o background animado) declarado nos defs como fill -->
  <text x="50%" text-anchor="middle" y="50%" fill="url(#pattern)" font-size="32pt">StackOverflow beta em Português</text>

  <defs>
    <!-- A declaração do gradient -->
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0">
      <!-- As cores do gradient -->
      <!-- No caso você poderia declarar quantas cores você desejar, especificando os percentuais de offset -->
      <stop offset="0%" style="stop-color:#33235b;" />
      <stop offset="25%" style="stop-color:#D62229;" />
      <stop offset="50%" style="stop-color:#E97639;" />
      <stop offset="75%" style="stop-color:#792042;" />
      <stop offset="100%" style="stop-color:#33235b;" />
    </linearGradient>

    <!-- Utilize dois gradientes em conjunto para uma animação perfeita  -->
    <!-- A declaração das animações -->
    <pattern id="pattern" x="0" y="0" width="100%" height="100%" patternUnits="userSpaceOnUse">
      <!-- Primeiro frame de animação, animando de 0% até 100% no eixo x-->
      <rect x="0" y="0" width="100%" height="100%" fill="url(#gradient)">
        <animate attributeType="XML" attributeName="x" from="0" to="100%" dur="7s" repeatCount="indefinite" />
      </rect>
      <!-- Segundo frame de animação, animando de -100% até 0% no eixo x, preenchendo a animação do frame anterior -->
      <rect x="-100%" y="0" width="100%" height="100%" fill="url(#gradient)">
        <animate attributeType="XML" attributeName="x" from="-100%" to="0" dur="7s" repeatCount="indefinite" />
      </rect>
    </pattern>
  </defs>
</svg>

The key changes you may need to make in the code to fit your case are:

  • Change the values of width and height of tag svg , to values in px as needed;
  • Change font size of text by assigning desired value to font-size of tag text ;
  • Change the text that should be displayed by assigning the desired text to the contents of the text tag
  • Change the colors and gradient proportions in the linearGradient tag with id=gradient ;
  • Change the animation speed of the text source background by changing the value of the dur attribute in the rect tags belonging to the pattern (Note: to maintain the consistency of the animation it is necessary that the value of the dur is the same in the two tags rect );
  • Example in jsFiddle

        
    14.04.2015 / 20:27
    5

    You can create a Timer javascript that increments and moves its background

    For example:

    $(function(){
        var x = 0;
        function transacao(){
            x-=100;
            $('h1.move').css('background-position', x + 'px 0');
        }
        transacao();
        setInterval(transacao, 10050);
    });
    

    Example online.

      

    Note: You should change the start or end color of the gradient so that there is no abrupt color change in the example.

    Edit - To apply this effect to the text instead of the background

    This css copies the background to the text, with the background -clip (from what I saw it does not seem to work for all browsers, I tested it on Chrome):

    background-clip: text;
    text-fill-color: transparent;
    
      

    Note: As quoted in @renan, background-clip: text only works in Chrome like this: -webkit-background-clip: text , and in the other browser it does not work, it would have to look for something else. :

    Online example, Chrome only

        
    14.04.2015 / 16:56
    4

    Using the CSS3 keyframe you can animate without any JS.

    @keyframes animatedBackground {
    	0% { background-position: -1145px 0; }
    	100% { background-position: 0 0; }
    }
    @-moz-keyframes animatedBackground {
    	0% { background-position: -1145px 0; }
    	100% { background-position: 0 0; }
    }
    @-webkit-keyframes animatedBackground {
    	0% { background-position: -1145px 0; }
    	100% { background-position: 0 0; }
    }
    @-ms-keyframes animatedBackground {
    	0% { background-position: -1145px 0; }
    	100% { background-position: 0 0; }
    }
    @-o-keyframes animatedBackground {
    	0% { background-position: -1145px 0; }
    	100% { background-position: 0 0; }
    }
    
    #header-animation {
        color: white;
        font-family: Georgia;
        text-align: center;
        line-height: 220px;
    	width: 100%; 
    	height: 200px;
    	background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2Y0NDczMCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjI2JSIgc3RvcC1jb2xvcj0iI2Y3ZjAyZSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUxJSIgc3RvcC1jb2xvcj0iIzJkYmExZCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9Ijc2JSIgc3RvcC1jb2xvcj0iIzIzNzVkYiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNkMTExMDAiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
        background: -moz-linear-gradient(left,  #f44730 0%, #f7f02e 26%, #2dba1d 51%, #2375db 76%, #d11100 100%); /* FF3.6+ */
    	background: -webkit-gradient(linear, left top, right top, color-stop(0%,#f44730), color-stop(26%,#f7f02e), color-stop(51%,#2dba1d), color-stop(76%,#2375db), color-stop(100%,#d11100)); /* Chrome,Safari4+ */
    	background: -webkit-linear-gradient(left,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* Chrome10+,Safari5.1+ */
    	background: -o-linear-gradient(left,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* Opera 11.10+ */
    	background: -ms-linear-gradient(left,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* IE10+ */
    	background: linear-gradient(to right,  #f44730 0%,#f7f02e 26%,#2dba1d 51%,#2375db 76%,#d11100 100%); /* W3C */
    	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f44730', endColorstr='#d11100',GradientType=1 ); /* IE6-8 */
    	background-position: 0px 0px;
    
    	animation: animatedBackground 10s linear infinite;
    	-moz-animation: animatedBackground 10s linear infinite;
    	-webkit-animation: animatedBackground 10s linear infinite;
    	-ms-animation: animatedBackground 10s linear infinite;
    	-o-animation: animatedBackground 10s linear infinite;
    }
    <h1 id="header-animation">Título</h1>
        
    14.04.2015 / 17:12
    3

    In the absence of a cross-browsers solution in CSS to apply a gradient to the background of a text, I suggest using canvas to achieve its goal. This example in W3Schools does exactly what you want, just missing animating the gradient with the time. Combining this technique with the method I described in another answer to make the animation via setInterval , we have: / p>

    var texto = "stackoverflow em Português";
    
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.font="30px Verdana";
    
    // As cores que compõem o degradê
    var cores = [
        [255,0,0],
        [255,255,0],
        [0,255,0],
        [0,0,255],
        [128,0,128]
    ];
    var shift = 1; // A transição entre uma e outra, de 0 a 1
    var passos = ["0", "0.25", "0.5", "0.75", "1"];
    
    // Faz uma média ponderada de cada componente das cores 1 e 2
    function calcular(cor1, cor2, progresso) {
      var ret = [];
      for ( var i = 0 ; i < cor1.length ; i++ )
        ret[i] = Math.round(cor2[i] * progresso + cor1[i] * (1 - progresso));
      return ret;
    }
    
    setInterval(function() {
        // Ajusta o progresso entre uma cor e outra
        shift -= 0.04;
        if ( shift < 0 ) { // Ao chegar a zero, circula as cores na lista
            shift = 1;
            cores.unshift(cores.pop()); // Retira-se a última e insere-a no início
        }
        
        // Create gradient
        var gradient=ctx.createLinearGradient(0,0,c.width,0);
        for ( var i = 0 ; i < 5 ; i++ ) {
            var anterior = (i == 0 ? 4 : i-1); // A última junta com a primeira
            var media = calcular(cores[anterior], cores[i], shift);
            var cor = "rgb(" + media.join(",") + ")";
            gradient.addColorStop(passos[i], cor);
        }
        
        // Fill with gradient
        ctx.fillStyle=gradient;
        ctx.fillText(texto,10,30); // Desenha o texto de fato
    }, 250);
    <canvas id="myCanvas" width="500"></canvas>

    Example in jsFiddle . Note that this approach is not without disadvantages:

  • You will have to set canvas within h1 (or instead of h1 ), and the text should be in a JavaScript variable;
  • If the screen is resized, or the font changed, the text will not automatically follow the changes - this needs to be done by code;
  • Not every browser supports canvas ( IE 8- does not support , the unless you use a shim ).
  • 14.04.2015 / 20:00
    2

    You can use a .gif file like background , removing all necessary implementation in CSS and Javascript. Example:

    body{
        background-image: url('http://i.stack.imgur.com/kx8MT.gif');
        background-size: cover;
    }
    d
        
    14.04.2015 / 16:58