Optimierung zeitbasierter CSS-Animationen mit neuen CSS-Funktionen

王林
Freigeben: 2024-08-21 06:49:12
Original
159 Leute haben es durchsucht

Geschrieben von Emmanuel Odioko✏️

Lange Zeit war die Erstellung zeitbasierter CSS-Animationen durch die eingeschränkte Unterstützung mathematischer Funktionen deutlich schwieriger. Eine herkömmliche Animation basierte auf Keyframes und Dauern, denen die Flexibilität zeitbasierter Aktualisierungen auf der Grundlage komplexer Berechnungen fehlte. Mit der Einführung von CSS-Funktionen wie mod(), Round() und trigonometrischen Funktionen können Entwickler nun erkunden, wie sie zeitbasierte Animationen in CSS beherrschen.

Was Sie wissen sollten, bevor Sie beginnen

Um das Beste aus diesem Artikel über zeitbasierte Animationen in CSS mit neuen CSS-Funktionen herauszuholen, sollten Sie über gute Kenntnisse von CSS-Animationen und -Übergängen verfügen. Sie sollten wissen, wie Sie Animationen mithilfe von @keyframes erstellen und deren Timing steuern. Sie sollten außerdem über grundlegende JavaScript-Kenntnisse verfügen, die sich mehr auf die Fähigkeit konzentrieren, DOM-Elemente zu manipulieren und auf Benutzerereignisse zu reagieren.

Schließlich wären ein Verständnis neuer CSS-Funktionen wie calc() und die Bereitschaft, neue Funktionen wie mod(), trigonometrische Funktionen einschließlich sin() und cos() sowie Round() zu erkunden, eine gute Grundlage.

Wenn Sie mit der Lektüre dieses Artikels fertig sind, werden Sie verstehen, wie Animationen traditionell mit JavaScript auf einer HTML-Leinwand implementiert wurden und wie sie im Vergleich zu den neueren CSS-Funktionen abschneiden. Wir werden verstehen, wie einfach die Verwendung von mod(),round() und trigonometrischen Funktionen gegenüber herkömmlichen CSS-Keyframes ist.

Optimizing CSS time-based animations with new CSS functions

Was sind zeitbasierte CSS-Animationen?

Zeitbasierte Animationen sind nicht neu – es gibt sie schon seit über einem Jahrzehnt. Einige sind kompliziert in der Anwendung, andere wiederum nicht. Kennen Sie diese CSS-Dateien, in denen mathematische Berechnungen im Vordergrund stehen? Dazu gehören zeitbasierte Animationen.

Wie der Name schon sagt, sind diese Animationen eng mit der Zeit verknüpft, da sich die Eigenschaften von Elementen wie Position, Größe, Farbe, Deckkraft usw. im Laufe der Zeit ändern. Die zeitbasierte CSS-Animation erzeugt sanfte Übergänge, verbessert das Erscheinungsbild von Webanwendungen und sorgt für ein besseres Benutzererlebnis.

Zeitbasierte CSS-Animationen bestehen im Wesentlichen aus einer definierten Start- und Endzeitleiste sowie Interpolationspunkten. Unter Interpolation versteht man hier die Berechnung von Zwischenwerten zwischen Beginn und Ende der Animation über einen bestimmten Zeitraum im Verlauf der Animation. Der Grund für die Interpolation besteht darin, einen reibungslosen Übergang vom Anfangs- zum Endzustand zu gewährleisten.

Zeitbasierte Animationen entstehen durch die Kombination von CSS-Variablen und einigen mathematischen Funktionen. Diese Einheit ermöglicht es Entwicklern, Animationen zu erstellen, die sich im Laufe der Zeit ändern, und führt zu flexibleren Animationen, von denen Keyframe-Animationen nur träumen können. Lassen Sie uns die Schlüsselkonzepte und ihre Funktionsweise aufschlüsseln.

Zeitbasierte Animationen aufschlüsseln

In diesem Abschnitt werden wir die allgemeine Struktur zum Erstellen zeitbasierter Animationen in Schlüsselkomponenten aufschlüsseln.

Ausgangszustand

Der Anfangszustand definiert die Starteigenschaften des Elements, bevor die Animation beginnt. Dies kann eine bestimmte Position, Größe, Farbe, Deckkraft usw. sein. Beispiel unten:

.box { opacity: 0; transform: translateY(-20px); }
Nach dem Login kopieren

Im obigen Code haben wir den Anfangszustand für ein Element mit der Klasse box, die seine Deckkraft und Transformationseigenschaften definiert.

Der Animationsauslöser gibt das Ereignis an, das die Animation initiiert. Zu den häufigsten Auslösern gehören Benutzerinteraktionen wie Klicks oder Hovers, Seitenladeereignisse oder bestimmte Bedingungen in der Anwendung, wie z. B. der Abschluss einer Aktion durch einen Benutzer.

Zu den Eigenschaften der Animation gehören die Animationsdauer, die Zeitfunktion, die Verzögerung, die Anzahl der Iterationen, die Richtung und der Füllmodus. Eine Animation kann einige oder alle dieser Eigenschaften haben. Ein Beispiel-Trigger mit dem Hover-Selektor ist unten dargestellt:

.box:hover { animation: fadeIn 1s ease-in-out forwards; }
Nach dem Login kopieren

Dies zeigt das Hinzufügen eines Animations-FadeIns, das ausgelöst wird, wenn der Mauszeiger über das Element mit der Klassenbox bewegt wird und eine Sekunde lang anhält. Das Animationsverhalten und das Timing werden ebenfalls festgelegt. Weitere Informationen zu Animations- und Übergangszeitfunktionen finden Sie in diesem Artikel.

Interpolationspunkte

Wie bereits erwähnt handelt es sich hierbei um Zwischenzustände der Animation an verschiedenen Punkten entlang der Zeitachse. Jeder Keyframe gibt die Eigenschaften des Elements zu einem bestimmten Zeitpunkt an und ermöglicht so schrittweise Übergänge zwischen dem Anfangs- und dem Endzustand. Eine Beispielimplementierung von Interpolationspunkten ist die CSS-Keyframes-Eigenschaft:

@keyframes fadeIn { 0% { opacity: 0; transform: translateY(-20px); } 100% { opacity: 1; transform: translateY(0); } }
Nach dem Login kopieren

Das obige Beispiel verwendet Keyframes, um die Eigenschaften der Einblendanimation bei Null und 100 Prozent des Animationsfortschritts zu definieren.

Common uses of time-based animations

Time-based animation has become increasingly essential in web applications as it helps with better user experience. The usage of these animations ranges from subtle micro-interactions to significant site transitions, giving web apps a more dynamic feel. Below are common use cases of these animations.

Micro-interactions

Micro-interactions are small, often subtle, and reusable animations that occur in response to user actions. These brief animations provide feedback. You may have come across animations such as pop-up warnings, loading spinners indicating ongoing processes, or a button indicating a click action. All of these are micro-interactions and consist of time-based animations.Optimizing CSS time-based animations with new CSS functionsImage source: https://userpilot.com/blog/micro-interaction-examples/[/caption]

In the image above, we have a submit button which shows a loader and a tick when the user clicks on it. The essence of these micro interactions is to commit to the user the process of the submission and the success of the operation.

Transitions

Site transitions are used to indicate state or page changes on a web application to create a fluid user experience using effects such as fading, sliding, or scaling elements. With time-based animations, these transitions are possible. Common transition effect applications are toggling navigation and side menus, parallax animations, opening and closing of modals, etc.

Image source: https://medium.com/@9cv9official/create-a-beautiful-hover-triggered-expandable-sidebar-with-simple-html-css-and-javascript-9f5f80a908d1[/caption] Image source: https://medium.com/@9cv9official/create-a-beautiful-hover-triggered-expandable-sidebar-with-simple-html-css-and-javascript-9f5f80a908d1

In the GIF above, there is a sidebar which uses a transition animation to expand the sidebar on a mouse hover event.

Exploring new CSS functions

Let’s get into the new mathematical CSS functions mod(), round(), and the trigonometric functions sin(), cos() and tan() while discussing each in detail.

Mod () function

Like the JavaScript modulo operator %, this function returns the remainder after an arithmetic modulus operation has been carried out on two operands. In essence, the modulus is the leftover value after the dividend is divided by the other operand, the divisor, and no more division can occur. In JavaScript, using the modulo operator will take the following form:10%4.

This operation would leave behind a Modulus of 2 as 10 is only divisible by the divisor 4 twice, leaving behind a remainder of 2. Similarly, the CSS Mod function would perform the same function with the following syntax instead: mod(10, 4).

It is also important to note that the modulus takes the sign of the divisor. As such, the result of mod(10, -4) would be -2 instead.

Mod() parameters and syntax

The mod() function primarily accepts two sets of parameters mod(dividend, divisor) which are essentially two comma-separated values. These operands must be of the same dimension for them to be valid and can take a variety of values as parameters thereby improving the range of its application. Operands passed to mod() can be numbers, percentages, or dimensions.

Mod() can also take in the unit of its operands (e.g. px, rem, vh, deg) and can also handle mathematical calculations as dividend or divisor. Below are some examples showing the use of this CSS function:

/* using  without units */ scale: mod(18, 7); /* result is 4 */ /*  and  with units */ height: mod(100vh, 30vh); /* result is 10vh */ width: mod(500px, 200px); /* result is 100px */ transform: rotate(mod(90deg, 20deg)); /* result is 10deg */ /* negative  and  with units */ height: mod(18rem, -4rem); /* result is 2rem */ rotate: mod (180deg, -100deg); /* result is 80deg */ /* working with calculations */ width: mod(40px*2, 15px); /* result is 5px */ transform: scale(mod(2*3, 1.8)); /* result is 0.6 */ rotate: mod(10turn, 8turn/2); /* result is 2turn */
Nach dem Login kopieren

The code block above shows different applications of the mod() in CSS styles.

While the examples shown use known values, time-based functions are expected to be used with CSS variables which are dynamic and make it possible for the styles to change values depending on the variable passed to the function. The outcome of the operation is then dependent on the calculation using the specified variables, and can produce a wider range of outcomes compared to when hardcoded values are used.

Below you’ll find the general syntax for all possibilities of mod() as illustrated by MDN:

 = mod(  ,  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Nach dem Login kopieren

In the syntax above, calc-sum represents the operands of the modulus operation. The syntax also shows the types of values calc-sum can contain and the possibility of negative and positive values. Furthermore, the syntax above also shows the possible calc-keywords e, pi, infinity, -infinity, and NaN.

round() function

The CSS round() function value is based on a specified rounding strategy. Note that strategy refers to the pattern of rounding the value such as rounding up or down, rounding to zero, rounding to the nearest occurrence of a number, etc..

round() parameters and syntax

The syntax for applying the CSS round() is given below:

round(, valueToRound, roundingInterval)
Nach dem Login kopieren

Here's a breakdown of the CSS round() function into smaller bits and highlights of the functions of each keyword and the possible values they can take.

rounding-strategy

The rounding strategy is the type of technique that would be used to round a specified value. This is optional (defaults to nearest if unspecified), and can be one of the following:

  • up — rounds value up to the nearest integer multiple of the specified roundingInterval. This operation is similar to JavaScript’s Math.ceil() method and will produce a more positive result if the value is negative
  • down — rounds valueToRound down to the nearest integer multiple of the specified roundingInterval. This is similar to JavaScript’s Math.floor() method and will produce a more negative result if the value is negative
  • nearest — rounds the valueToRound to the nearest integer multiple of roundingInterval. The result obtained may be higher or lower than the value, depending on how close it is to a multiple of the roundingInterval
  • to-zero — rounds the value to the nearest integer multiple of roundingInterval closer to/towards zero and is equivalent to JavaScript’s trunc() method

valueToRound

This is the value we intend to round using the function, and it can be a , , , or even mathematical expressions like we had in the mod() function.

roundingInterval

The rounding interval refers to the interval a value is rounded with a reference to. This entry can be a , , ,or a mathematical expression.

Below is an example illustrating the use of the CSS round() function:

     Document  
   
rounded 50%
rounded 100%
rounded 25%
Nach dem Login kopieren

In this example, we used round() and CSS variables to round values to a specified roundingInterval in the style of each element. Below is the outcome of this example:Optimizing CSS time-based animations with new CSS functionsThe formal syntax of the CSS round() function according to MDN docs is given by the following:

 = round( ? ,  , ? )  = nearest | up | down | to-zero  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Nach dem Login kopieren

In the syntax above, rounding-strategy is the intended rounding pattern and calc-sum represents the operands. The formula also shows the possible entries for rounding-strategy and calc-sum. Finally, it outlines the possible calc-keywords e, pi, infinity, -infinity, and NaN.

Trigonometric functions

The CSS trigonometric functions perform the same operations as in mathematics, as such, the sin() function returns the sine of a number as a value between the range of -1 and 1, cos() returns the cosine of a value, and tan() returns the tangent of a specified value.

Arguments passed to these functions must be either a number or an angle, and they will be treated as radians. Units such as deg and turn represent angle and can be used with arguments here.

Example applications of these functions are shown below:

scale: sin(45deg); /* result is 0.7071067811865475 */ rotate: cos(30deg); /* result is 0.8660254037844387 */ height: calc(50px * tan(30deg)); /* result is 28.86751345948129px */
Nach dem Login kopieren

All trigonometric CSS functions bear similarity, taking in only a single parameter that is resolved to an angle.

Parameters and syntax of sin()

Sin() takes in only one parameter which must be a number or angle, or a mathematical expression that resolves to either of them. The syntax of sin() is as follows: \

sin(angle)
Nach dem Login kopieren

The formal syntax of sin() is shown below: \

 = sin(  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Nach dem Login kopieren

The syntax above shows the possible values for calc-sum and calc-keyword.

Parameters and syntax of cos()

The parameter of cos() is either a number, an angle, or contains a single calculation that must resolve to either type.

As such, the syntax for cos() is the following:

cos(angle)
Nach dem Login kopieren

The formal syntax of all possibilities of cos() is below:

 = cos(  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Nach dem Login kopieren

Where calc-sum is the parameter, calc-value is the allowed types of parameters, and calc-keywords are possible units that can be added to the mathematical expression.

Parameters and syntax of tan()

The tan() function also takes a number, an angle, or a single calculation that must resolve to either type, similar to the other trigonometric functions. The syntax of tan() is given by the following:

tan(angle)
Nach dem Login kopieren

The formal syntax of this function is shown below:

 = tan(  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Nach dem Login kopieren

This syntax shows all possible values of calc-sum, the operand, and the calc-keyword.

Comparing timing animations between CSS functions and keyframes

In this section, we will create an animation using CSS functions, keyframes for an alternative, and JavaScript for a second alternative. In the end, we will compare the code and contrast the approaches to determine the benefits of usingCSS functions in creating CSS animations over other options.

Creating animation with CSS functions

Let's start by creating our music beat bar animation using CSS functions. This animation focuses on animating multiple bars, changing the property of the height and background colors using values generated with CSS functions:

     Beats Bar Animation with CSS Functions  
  
Nach dem Login kopieren

Here’s a breakdown of the code block above:

  • Created a root animation to change the value of a variable --t infinitely
  • Styled the body and container class
  • Created the initial state for the bar class and declared some variables we would use in our animation. Here we also created a transition property and used round() and mod() CSS functions to generate dynamic values for the background colors of the bars
  • Next, we applied a height transition to each of the bars, depending on the values obtained from the variables
  • Finally, we have the HTML element structure

The code above produces the following animation:Optimizing CSS time-based animations with new CSS functions

Recreating the animation with CSS keyframes

In this section, we will rebuild the sound bar animation, but we’ll use animations and CSS keyframes instead:

     Beats Bar Animation with CSS Keyframes  
  
Nach dem Login kopieren

In the code above, we have styles for the body, container, and bar elements. We added an initial fallback animation state bounce and defined the animation properties with keyframes. Furthermore, we had to create separate keyframes animations for each bar’s height and background color change. The output of this animation is shown below:Optimizing CSS time-based animations with new CSS functions

Creating the animation with JavaScript

Here, we will demonstrate how we can work with HTML, CSS, and JavaScript to recreate the animation in the previous section:

     Beats Bar Animation with JavaScript  
  
Nach dem Login kopieren

In the code above, we styled the elements with CSS and created the HTML structure. We used JavaScript to select all elements with the class bar and also declared the variables. Next, we used a set of mathematical calculations to offset the bar height property and apply visual changes to the background gradient. The result is shown in the GIF below:Optimizing CSS time-based animations with new CSS functions

Code comparison

Let’s compare these different methods using certain technical aspects:

Aspect technique Fonctions CSS Images clés JavaScript
Longueur du code Généralement plus court, utilisant des variables et des fonctions Peut être long selon le nombre d'images clés et les points d'interpolation définis La longueur dépend de facteurs tels que les éléments à manipuler, la logique et les propriétés à appliquer.
Facilité de mise en œuvre Simple pour des motifs dynamiques et répétitifs Simple pour des animations prédéfinies Gestion et interaction de logiques complexes
Performances Hautes performances, déchargées sur le GPU et moins gourmandes en CPU Hautes performances, déchargées sur le GPU, moins gourmandes en CPU Peut être moins performant, en fonction du moteur JavaScript et de la quantité de JavaScript à exécuter sur le Web
Contrôle Dynamique et flexible Cadres statiques prédéfinis Très dynamique et interactif
Entretien Facile à maintenir, syntaxe concise Facile à entretenir mais peut devenir verbeux Peut devenir complexe et plus difficile à maintenir, et apporter des modifications à la logique
Types d'animation Idéal pour les animations mathématiques simples, répétitives Idéal pour les animations détaillées en plusieurs étapes Idéal pour les animations interactives et réactives
Réutilisabilité Haute réutilisabilité avec les variables CSS puisque les fonctions mathématiques peuvent créer différentes valeurs pour la même variable Modéré, nécessite une duplication pour différentes animations Haute réutilisabilité avec fonctions et logique
Compatibilité des navigateurs `Mod()` et `Round()` ne sont pas compatibles avec les navigateurs Opera et Samsung, le reste va bien Les images clés existent depuis un moment, elles seront donc compatibles pour les animations basées sur le temps JavaScript est compatible avec tous les navigateurs pour les animations temporelles

D'après ce qui précède, nous pouvons voir que les fonctions CSS lorsqu'elles sont utilisées pour l'animation excellent en termes de simplicité, de réutilisabilité du code, de contrôle et de performances par rapport à d'autres implémentations.

Conclusion

Au cours de l'article, nous avons couvert les animations temporelles allant de mod() à round() puis aux fonctions trigonométriques.

Nous avons également comparé ces fonctions avec les images clés et Javascript, et nous avons pu constater que l'animation basée sur le temps se développe principalement grâce à leur simplicité, leur réutilisabilité améliorée et leur optimisation des performances, car elles sont légères et moins susceptibles d'avoir un impact sur les performances par rapport à animations complexes.

Cela, à son tour, contribue à améliorer l'expérience utilisateur. Continuez à explorer ces fonctions et continuez à coder !!


Votre interface monopolise-t-elle le processeur de vos utilisateurs ?

À mesure que les interfaces Web deviennent de plus en plus complexes, les fonctionnalités gourmandes en ressources exigent de plus en plus du navigateur. Si vous souhaitez surveiller et suivre l'utilisation du processeur côté client, l'utilisation de la mémoire et bien plus encore pour tous vos utilisateurs en production, essayez LogRocket.

Optimizing CSS time-based animations with new CSS functions

LogRocket est comme un DVR pour les applications Web et mobiles, enregistrant tout ce qui se passe dans votre application Web, application mobile ou site Web. Au lieu de deviner pourquoi les problèmes surviennent, vous pouvez regrouper et créer des rapports sur les principales mesures de performances du front-end, rejouer les sessions utilisateur avec l'état de l'application, enregistrer les requêtes réseau et faire apparaître automatiquement toutes les erreurs.

Modernisez la façon dont vous déboguez les applications Web et mobiles : commencez à surveiller gratuitement.

Das obige ist der detaillierte Inhalt vonOptimierung zeitbasierter CSS-Animationen mit neuen CSS-Funktionen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!