Texto de rastreo de Star Wars | Programar Plus

La apertura de Star Wars es icónica. El efecto del texto desplazándose tanto hacia arriba como fuera de la pantalla fue tanto un efecto especial increíblemente genial para una película en 1977 como un estilo tipográfico genial que era completamente nuevo en ese momento.

¡Podemos lograr un efecto similar con HTML y CSS! Esta publicación trata más sobre cómo obtener ese efecto de texto deslizante en lugar de intentar recrear la secuencia de apertura completa de Star Wars o hacer coincidir los estilos exactos utilizados en la película, así que vayamos a un lugar donde este es el resultado final:

Vea la introducción de Pen Star Wars de Geoff Graham (@geoffgraham) en CodePen.

El HTML básico

Primero, configuremos HTML para el contenido:

<section class="star-wars">

  <div class="crawl">
    
    <div class="title">
      <p>Episode IV</p>
      <h1>A New Hope</h1>
    </div>
    
    <p>It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire.</p>     
    <p>During the battle, Rebel spies managed to steal secret plans to the Empire’s ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet.</p>
    <p>Pursued by the Empire’s sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy…</p>

  </div>

</section>

Esto nos da todas las piezas que necesitamos:

  • Un contenedor llamado star-wars que usaremos para posicionar el contenido. Esto también es necesario porque usaremos el perspective Propiedad CSS, donde tener un elemento padre es una forma útil de agregar profundidad o sesgar el elemento secundario transform propiedad.
  • Un contenedor llamado crawl que contendrá el texto real y será el elemento al que aplicamos la animación CSS.
  • ¡El contenido!

Es posible que haya notado que el título de la película está envuelto en un extra <div> contenedor llamado title. Esto no es necesario, pero podría proporcionarle opciones de estilo adicionales en caso de que las necesite.

El CSS básico

El truco consiste en imaginar un espacio tridimensional donde el texto se arrastra verticalmente por la Y-axis y a lo largo del Z-axis. Esto da la impresión de que el texto se desliza hacia arriba en la pantalla y se aleja del espectador al mismo tiempo.

Los ejes X, Y y Z de un plano tridimensional

Primero, configuremos el documento <body> para que la pantalla no se pueda desplazar. Queremos que el texto aparezca desde la parte inferior de la pantalla sin que el espectador pueda desplazarse y ver el texto antes de que ingrese. Nosotros podemos usar overflow: hidden Para hacer eso:

body {
  /* Force the body to fill the entire screen */
  width: 100%;
  height: 100%;
  /* Hide elements that flow outside the viewable space */
  overflow: hidden;
  /* Black background for the screen */
  background: #000;
}

Ahora podemos pasar a diseñar nuestro star-wars container, que es el elemento principal de nuestra demostración:

.star-wars {
  /* Flexbox to center the entire element on the screen */
  display: flex;
  justify-content: center;
  /* This is a magic number based on the context in which this snippet is used and effects the perspective */
  height: 800px;
  /* This sets allows us to transform the text on a 3D plane, and is somewhat a magic number */
  perspective: 400px;
  /* The rest is totally up to personal styling preferences */
  color: #feda4a;
  font-family: 'Pathway Gothic One', sans-serif;
  font-size: 500%;
  font-weight: 600;
  letter-spacing: 6px;
  line-height: 150%;
  text-align: justify;
}

A continuación, podemos aplicar estilos a la crawl elemento. Nuevamente, este elemento es importante porque contiene las propiedades que transformarán el texto y lo animarán.

.crawl {
  /* Position the element so we can adjust the top property in the animation */
  position: relative;
  /* Making sure the text is fully off the screen at the start and end of the animation */
  top: -100px;
  /* Defines the skew origin at the very center when we apply transforms on the animation */
  transform-origin: 50% 100%;
}

Hasta ahora, tenemos un montón de texto atractivo, pero no está sesgado ni animado. Hagamos que eso suceda.

¡Animación!

Esto es lo que realmente te importa, ¿verdad? Primero, vamos a definir el @keyframes para la animación. La animación está haciendo un poco más que animar para nosotros, porque vamos a agregar nuestro transform propiedades aquí, en particular para el movimiento a lo largo de la Z-axis. Comenzaremos la animación en 0% donde el texto está más cerca del espectador y se encuentra debajo de la pantalla, fuera de la vista, luego finalice la animación en 100% donde está lejos del espectador y fluye hacia arriba y sobre la parte superior de la pantalla.

/* We're calling this animation "crawl" */
@keyframes crawl {
  0% {
    /* The element starts below the screen */
    top: 0;
    /* Rotate the text 20 degrees but keep it close to the viewer */
    transform: rotateX(20deg) translateZ(0);
  }
  100% { 
    /* This is a magic number, but using a big one to make sure the text is fully off the screen at the end */
    top: -6000px;
    /* Slightly increasing the rotation at the end and moving the text far away from the viewer */
    transform: rotateX(25deg) translateZ(-2500px);
  }
}

Ahora, apliquemos esa animación en el .crawl elemento:

.crawl {
  /* Position the element so we can adjust the top property in the animation */
  position: relative;
  /* Defines the skew origin at the very center when we apply transforms on the animation */
  transform-origin: 50% 100%;
  /* Adds the crawl animation, which plays for one minute */
  animation: crawl 60s linear;
}

Tiempos divertidos con ajuste fino

Puede divertirse un poco más con las cosas una vez que el efecto principal esté en su lugar. Por ejemplo, podemos agregar un pequeño desvanecimiento en la parte superior de la pantalla para acentuar el efecto del texto arrastrándose en la distancia:

.fade {
  position: relative;
  width: 100%;
  min-height: 60vh;
  top: -25px;
  background-image: linear-gradient(0deg, transparent, black 75%);
  z-index: 1;
}

Agregue ese elemento a la parte superior del HTML y el texto fluirá detrás de un degradado que va de transparente al mismo fondo que el <body>:

<div class="fade"></div>

El ejemplo completo

Aquí está el código completo de esta publicación reunido.

<div class="fade"></div>

<section class="star-wars">

  <div class="crawl">

    <div class="title">
      <p>Episode IV</p>
      <h1>A New Hope</h1>
    </div>
    
    <p>It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire.</p>      
    <p>During the battle, Rebel spies managed to steal secret plans to the Empire’s ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet.</p>
    <p>Pursued by the Empire’s sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy…</p>

  </div>

</section>
body {
  width: 100%;
  height: 100%;
  background: #000;
  overflow: hidden;
}

.fade {
  position: relative;
  width: 100%;
  min-height: 60vh;
  top: -25px;
  background-image: linear-gradient(0deg, transparent, black 75%);
  z-index: 1;
}

.star-wars {
  display: flex;
  justify-content: center;
  position: relative;
  height: 800px;
  color: #feda4a;
  font-family: 'Pathway Gothic One', sans-serif;
  font-size: 500%;
  font-weight: 600;
  letter-spacing: 6px;
  line-height: 150%;
  perspective: 400px;
  text-align: justify;
}

.crawl {
  position: relative;
  top: 9999px;
  transform-origin: 50% 100%;
  animation: crawl 60s linear;
}

.crawl > .title {
  font-size: 90%;
  text-align: center;
}

.crawl > .title h1 {
  margin: 0 0 100px;
  text-transform: uppercase;
}

@keyframes crawl {
  0% {
    top: 0;
    transform: rotateX(20deg)  translateZ(0);
  }
  100% { 
    top: -6000px;
    transform: rotateX(25deg) translateZ(-2500px);
  }
}

Otros ejemplos

Algunas otras personas han hecho interpretaciones más fieles de la apertura de Star Wars utilizando otras técnicas que las que se cubren aquí en esta publicación.

Tim Pietrusky tiene una versión bellamente orquestada que utiliza top para el movimiento y opacity para crear el efecto de desvanecimiento:

Vea el rastreo de apertura de Pen Star Wars de 1977 por Tim Pietrusky (@TimPietrusky) en CodePen.

Usos de Yukulélé margin para mover el a lo largo de la pantalla:

Vea el rastreo de apertura de Pen Pure CSS Star Wars por Yukulélé (@yukulele) en CodePen.

Usos de Karottes transform muy parecido a esta publicación, pero se basa más en TranslateY para mover el texto a lo largo del Y-axis.

Vea el Pen Star Wars Crawl de Karottes (@Karottes) en CodePen.