Move background of text

Asked

Viewed 338 times

5

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

I need this gradient to be applied to the source (not behind the text) and to keep moving from left to right indefinitely. How I do this with CSS or Jquery?

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

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 */
  • 1

    Check whether these answers to that question, they no longer help you.

  • Look all worked out but I need the background to be inside the Font and not behind the letter. Type of time the letter color to be black will be a degrade. Thank you

  • @Joaonivaldo you did not explain this in the question.

  • Pardon I expressed myself badly at the beginning of the explanation.

  • As a matter of curiosity, there is -webkit-background-clip:text that does just what it needs: Apply the color of background in the text. But this is not a standard value, it does not exist in the specification and was implemented only in browsers -Webkit-. I believe you will have to use Javascript even - see on Google Chrome - who knows someday become something standardized. ^^

5 answers

6


In the absence of an answer that reaches 100% the problems of AP, I risk publishing an alternative using SVG, consisting 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 main changes you may need to make in the code to adjust to your case are:

  1. Change the values of width and height tag svg, for values in px as needed;
  2. Change the font size of the text by setting the desired value in font-size tag text;
  3. Change the text that should be displayed by assigning the desired text to the tag content text;
  4. Change colors and gradient proportions in tag linearGradient with id=gradient;
  5. Change the animation speed of the text font background by changing the attribute value dur in the tags rect belonging to the pattern (Note: to maintain the consistency of the animation it is necessary that the value of the attribute dur be the same in both tags rect);

Example in jsFiddle

  • 1

    Thank you very much gave it right.

  • @Joaonivaldo, I’m glad I could help you =). Since the answer was marked as accepted, I tried to improve it. I commented more on the answer and the codes, demonstrating what each part is and what it does. So that this answer can also help other people with the same problem as yours.

5

You can create a Timer javascript that is increasing and moving its background

For example:

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

Online example.

Note: You must change the start or end color of the degrade, so that there is no abrupt color change as in the example.


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

That one css copies the background for the text, with the attribute background clip(From what I saw it doesn’t look like it works for every browser, I tested it in Chrome):

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

Note: As quoted in the comments by @Renan, background-clip: text only works in Chrome this way: -webkit-background-clip: text, and other browser does not work, would have to look for something alternative. :(

Online example, only in Chrome

  • +1 I was thinking of something like this, but you went a lot faster... :) I would just like to suggest - to reduce the load of JS code - that you use a much larger range in conjunction with a CSS transition. Example (without all the prefixes for transition; test on Chrome).

  • @mgibsonbr, quick. = ) hehe. Uhm, when I left for lunch I thought about it, which add a transition, to make the transaction smoother. Now with your suggestion, I will update the reply, thanks for the suggestion.

  • There is no background-clip:text in the Fernando specification, this value text was implemented only in Webkit browsers. Try opening the same online example in Firefox.

  • @Renan, you’re right, I saw the property on MDN, and I thought it worked for the new browsers.

4

Using 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>

3

In the absence of a solution cross-browsers in CSS to apply a gradient to background of a text, I suggest the use of canvas to achieve its objective. This example in W3schools does exactly what you want, just missing animate the gradient over time. Combining this technique with the method I described in another reply to do the animation via setInterval, we have:

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:

  1. You’ll have to put the canvas within the h1 (or instead of the h1), and the text must be in a Javascript variable;
  2. If the screen is resized, or the font changed, the text will not automatically track changes - this needs to be done by code;
  3. Not all browser supports canvas (IE 8- does not support, unless used one Shim).
  • +1 . It is one of the only alternatives even, or so or with svg. =)

2

You can use a file . gif like the 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

  • I would like to use CSS and at most Jquery would not like to have to create animation in gif, because the text is very large and the image will be heavy. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.