Écrit par Emmanuel Odioko✏️
Pendant longtemps, la prise en charge limitée des fonctions mathématiques rendait la création d'animations CSS basées sur le temps beaucoup plus difficile. Une animation traditionnelle reposait sur des images clés et des durées dépourvues de la flexibilité des mises à jour temporelles basées sur des calculs complexes. Avec l'introduction de fonctions CSS telles que mod(), round() et les fonctions trigonométriques, les développeurs peuvent désormais explorer comment maîtriser les animations temporelles en CSS.
Pour tirer le meilleur parti de cet article sur les animations temporelles en CSS à l'aide de nouvelles fonctions CSS, vous devez avoir une bonne compréhension des animations et des transitions CSS. Vous devriez être capable de savoir comment créer des animations à l'aide de @keyframes et contrôler leur timing. Vous devez également avoir une compréhension de base de JavaScript, en vous concentrant davantage sur la capacité de manipuler des éléments DOM et de répondre aux événements utilisateur.
Enfin, une compréhension des nouvelles fonctions CSS comme calc() et une volonté d'explorer des fonctionnalités émergentes comme mod(), des fonctions trigonométriques incluant sin() et cos() et round() constitueraient une bonne base.
Au moment où vous aurez fini de lire cet article, vous comprendrez comment les animations étaient traditionnellement implémentées sur un canevas HTML à l'aide de JavaScript et comment elles se comparent aux nouvelles fonctions CSS. Nous comprendrons la facilité d'utilisation des fonctions mod(),round() et trigonométriques par rapport aux images clés CSS traditionnelles.
Les animations basées sur le temps ne sont pas nouvelles : elles existent depuis plus d'une décennie. Certains sont compliqués à utiliser, d’autres non. Vous connaissez ces fichiers CSS où les calculs mathématiques sont primaires ? Les animations temporelles en font partie.
Comme leur nom l'indique, ces animations sont étroitement liées au temps, dans la mesure où les propriétés des éléments, telles que la position, la taille, la couleur, l'opacité, etc., changent avec le temps. L'animation temporelle CSS produit des transitions fluides améliorant la sensation des applications Web et offrant une meilleure expérience utilisateur.
Les animations CSS basées sur le temps consistent principalement en une chronologie de début et de fin définie et des points d'interpolation. L'interpolation fait ici référence au calcul de valeurs intermédiaires entre le début et la fin de l'animation sur une durée donnée au fur et à mesure de l'avancement de l'animation. Le but de l'interpolation est d'assurer une transition en douceur de l'état initial à l'état final.
Les animations basées sur le temps se produisent avec la combinaison de variables CSS et de quelques fonctions mathématiques. Cette unité permet aux développeurs de créer des animations qui changent au fil du temps et aboutissent à des animations plus flexibles dont les animations d'images clés ne peuvent que rêver. Décomposons les concepts clés et leur fonctionnement.
Dans cette section, nous décomposerons la structure générale de création d'animations temporelles en composants clés.
L'état initial définit les propriétés de départ de l'élément avant le début de l'animation. Il peut s'agir d'une position, d'une taille, d'une couleur, d'une opacité spécifiées, etc. Exemple ci-dessous :
.box { opacity: 0; transform: translateY(-20px); }
Dans le code ci-dessus, nous avons l'état initial d'un élément avec la classe box qui définit ses propriétés d'opacité et de transformation.
Le déclencheur d'animation spécifie l'événement qui lance l'animation. Les déclencheurs courants incluent les interactions de l'utilisateur telles que les clics ou les survols, les événements de chargement de page ou les conditions spécifiques de l'application telles que l'exécution d'une action par un utilisateur.
Les propriétés de l'animation incluent la durée de l'animation, la fonction de synchronisation, le délai, le nombre d'itérations, la direction et le mode de remplissage. Une animation peut avoir tout ou partie de ces propriétés. Un exemple de déclencheur avec le sélecteur de survol est présenté ci-dessous :
.box:hover { animation: fadeIn 1s ease-in-out forwards; }
Cela montre l'ajout d'un fondu d'animation qui se déclenche lorsque l'élément avec la zone de classe est survolé et dure une seconde. Le comportement et le timing de l'animation sont également spécifiés. Lisez cet article pour plus d’informations sur les fonctions d’animation et de synchronisation de transition.
Comme indiqué précédemment, il s'agit d'états intermédiaires de l'animation à différents points de la chronologie. Chaque image clé spécifie les propriétés de l'élément à un moment particulier, permettant des transitions progressives entre les états initial et final. Un exemple d'implémentation de points d'interpolation est la propriété CSS keyframes :
@keyframes fadeIn { 0% { opacity: 0; transform: translateY(-20px); } 100% { opacity: 1; transform: translateY(0); } }
L'exemple ci-dessus utilise des images clés pour définir les propriétés de l'animation fadeIn à zéro et 100 % de la progression de l'animation.
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 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.Image 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.
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.
Let’s get into the new mathematical CSS functions mod(), round(), and the trigonometric functions sin(), cos() and tan() while discussing each in detail.
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.
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:
/* usingwithout 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 */
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
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.
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..
The syntax for applying the CSS round() is given below:
round(, valueToRound, roundingInterval)
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.
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:
This is the value we intend to round using the function, and it can be a
The rounding interval refers to the interval a value is rounded with a reference to. This entry can be a
Below is an example illustrating the use of the CSS round() function:
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:The 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
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.
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 */
All trigonometric CSS functions bear similarity, taking in only a single parameter that is resolved to an angle.
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)
The formal syntax of sin() is shown below: \
= sin( ) = [ [ '+' | '-' ] ]* = [ [ '*' | '/' ] ]* = | | | | ( ) = e | pi | infinity | -infinity | NaN
The syntax above shows the possible values for calc-sum and calc-keyword.
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)
The formal syntax of all possibilities of cos() is below:
= cos( ) = [ [ '+' | '-' ] ]* = [ [ '*' | '/' ] ]* = | | | | ( ) = e | pi | infinity | -infinity | NaN
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.
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)
The formal syntax of this function is shown below:
= tan( ) = [ [ '+' | '-' ] ]* = [ [ '*' | '/' ] ]* = | | | | ( ) = e | pi | infinity | -infinity | NaN
This syntax shows all possible values of calc-sum, the operand, and the calc-keyword.
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.
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:
Here’s a breakdown of the code block above:
The code above produces the following animation:
In this section, we will rebuild the sound bar animation, but we’ll use animations and CSS keyframes instead:
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:
Here, we will demonstrate how we can work with HTML, CSS, and JavaScript to recreate the animation in the previous section:
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:
Let’s compare these different methods using certain technical aspects:
기술적인 측면 | CSS 기능 | 키프레임 | 자바스크립트 |
---|---|---|---|
코드 길이 | 일반적으로 더 짧으며 변수와 함수를 사용합니다 | 키프레임 수와 정의된 보간점에 따라 시간이 길어질 수 있습니다 | 길이는 조작할 요소, 논리, 적용할 속성 등의 요소에 따라 달라집니다. |
구현 용이성 | 동적이며 반복적인 패턴을 위한 단순함 | 미리 정의된 애니메이션은 간단합니다 | 복잡한 논리 처리 및 상호 작용 |
성능 | 고성능, GPU로 오프로드, CPU 사용량이 적음 | 고성능, GPU로 오프로드, CPU 사용량이 적음 | JavaScript 엔진과 웹에서 실행되는 JavaScript의 양에 따라 성능이 저하될 수 있습니다 |
컨트롤 | 동적이며 유연함 | 정적, 사전 정의된 프레임 | 매우 역동적이고 대화형입니다 |
유지관리 | 간편한 유지 관리, 간결한 구문 | 유지관리가 쉽지만 장황해질 수 있음 | 복잡해지고 유지 관리가 어려워질 수 있으며 로직을 변경할 수 있습니다 |
애니메이션 유형 | 단순하고 반복적인 수학적 애니메이션에 가장 적합 | 상세한 다단계 애니메이션에 적합 | 대화형 및 반응형 애니메이션에 가장 적합 |
재사용성 | 수학 함수가 동일한 변수에 대해 서로 다른 값을 생성할 수 있으므로 CSS 변수의 높은 재사용성 | 보통, 다양한 애니메이션에 중복이 필요함 | 함수와 로직을 통한 높은 재사용성 |
브라우저 호환성 | `Mod()` 및 `Round()`는 Opera 및 Samsung 브라우저와 호환되지 않으며 나머지는 괜찮습니다 | 키프레임은 한동안 사용되어 왔기 때문에 시간 기반 애니메이션과 호환됩니다 | JavaScript는 시간 기반 애니메이션을 위해 모든 브라우저와 호환됩니다 |
위에서 애니메이션에 사용될 때 CSS 기능이 다른 구현에 비해 단순성, 코드 재사용성, 제어 및 성능이 우수하다는 것을 알 수 있습니다.
이 기사에서는 mod(), round(), 삼각 함수에 이르는 시간 기반 애니메이션을 다루었습니다.
또한 이러한 기능을 키프레임 및 Javascript와 비교한 결과, 시간 기반 애니메이션은 복잡한 애니메이션에 비해 가볍고 성능에 영향을 미칠 가능성이 적기 때문에 주로 단순성, 향상된 재사용성 및 성능 최적화로 인해 성장한다는 것을 알 수 있었습니다.
이는 결과적으로 사용자 경험을 향상하는 데 도움이 됩니다. 계속해서 이러한 기능을 탐색하고 코딩을 계속하세요!!
웹 프런트엔드가 점점 더 복잡해짐에 따라 리소스를 많이 사용하는 기능은 브라우저에서 점점 더 많은 것을 요구합니다. 프로덕션에 있는 모든 사용자의 클라이언트 측 CPU 사용량, 메모리 사용량 등을 모니터링하고 추적하는 데 관심이 있다면 LogRocket을 사용해 보세요.
LogRocket은 웹 앱, 모바일 앱 또는 웹사이트에서 일어나는 모든 일을 기록하는 웹 및 모바일 앱용 DVR과 같습니다. 문제가 발생한 이유를 추측하는 대신 주요 프런트엔드 성능 지표를 집계 및 보고하고, 애플리케이션 상태와 함께 사용자 세션을 재생하고, 네트워크 요청을 기록하고, 모든 오류를 자동으로 표시할 수 있습니다.
웹 및 모바일 앱 디버깅 방법을 현대화하세요. 무료로 모니터링을 시작해 보세요.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!