Mengoptimumkan animasi berasaskan masa CSS dengan fungsi CSS baharu

王林
Lepaskan: 2024-08-21 06:49:12
asal
159 orang telah melayarinya

Written by Emmanuel Odioko✏️

For a long time, the limited support for math functions made creating time-based CSS animations much more challenging. A traditional animation relied on keyframes and durations lacking the flexibility of time-based updates based on complex calculations. With the introduction of CSS functions like mod(), round(), and trigonometric functions, developers can now explore how to master time-based animations in CSS.

Things to know before you begin

To get the most out of this piece about time-based animations in CSS using new CSS functions, you should have a good understanding of CSS animations and transitions. You should be able to know how to create animations using @keyframes and control their timing. You should also have a basic understanding of JavaScript focusing more on the ability to manipulate DOM elements and respond to user events.

Lastly, an understanding of new CSS functions like calc(), and a readiness to explore emerging features like mod(), trigonometric functions including sin() and cos(), and round() would make a good foundation.

By the time you are done reading this article, you will understand how animations were traditionally implemented on an HTML canvas using JavaScript and how they compare to the newer CSS functions. We will understand the ease of using mod(),round(), and trigonometric functions over traditional CSS keyframes.

Optimizing CSS time-based animations with new CSS functions

What are CSS time-based animations?

Time-based animations are not new — they’ve been around for over a decade. Some are complicated to use, while others are not. You know those CSS files where mathematical calculations are primary? Time-based animations are part of those.

As the name implies, these animations are closely related to time, in that the properties of elements, such as position, size, color, opacity, etc., change over time. CSS time-based animation produces smooth transitions enhancing the feel of web applications and providing a better user experience.

Time-based CSS animations primarily consist of a defined start and end timeline and interpolation points. Interpolation here refers to the calculation of intermediate values between the start and end of the animation over a given duration as the animation progresses. The reason for interpolation is to provide a smooth transition from the initial to the final state.

Time-based animations happen with the combination of both CSS variables and a few mathematical functions. This unity enables developers to create animations that change over time and results in more flexible animations that keyframe animations can only dream of. Let's break down the key concepts and how they work.

Breaking down time-based animations

In this section, we will break down the general structure for creating time-based animations into key components.

Initial state

The initial state defines the element’s starting properties before the animation begins. This could be a specified position, size, color, opacity, etc. Example below:

.box { opacity: 0; transform: translateY(-20px); }
Salin selepas log masuk

In the code above, we have the initial state for an element with the class box which defines its opacity and transform properties.

The animation trigger specifies the event that initiates the animation. Common triggers include user interactions such as clicks or hovers, page load events, or specific conditions in the application such as completion of an action by a user.

The properties of the animation include the animation duration, timing function, delay, iteration count, direction, and fill mode. An animation may have some or all of these properties. An example trigger with the hover selector is shown below:

.box:hover { animation: fadeIn 1s ease-in-out forwards; }
Salin selepas log masuk

This shows the addition of an animation fadeIn which is triggered when the element with the class box is hovered on and lasts for a second. The animation behavior and timing are also specified. Read this article for more information on animation and transition timing functions.

Interpolation points

As stated earlier, these are intermediate states of the animation at various points along the timeline. Each keyframe specifies the properties of the element at a particular moment, allowing for gradual transitions between the initial and final states. An example implementation of interpolation points is the CSS keyframes property:

@keyframes fadeIn { 0% { opacity: 0; transform: translateY(-20px); } 100% { opacity: 1; transform: translateY(0); } }
Salin selepas log masuk

The example above uses keyframes to define the properties of the fadeIn animation at zero and 100 percent of the animation’s progress.

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 */
Salin selepas log masuk

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
Salin selepas log masuk

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)
Salin selepas log masuk

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%
Salin selepas log masuk

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
Salin selepas log masuk

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 */
Salin selepas log masuk

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)
Salin selepas log masuk

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

 = sin(  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Salin selepas log masuk

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)
Salin selepas log masuk

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

 = cos(  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Salin selepas log masuk

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)
Salin selepas log masuk

The formal syntax of this function is shown below:

 = tan(  )  =  [ [ '+' | '-' ]  ]*  =  [ [ '*' | '/' ]  ]*  =  |  |  |  | (  )  = e | pi | infinity | -infinity | NaN
Salin selepas log masuk

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  
Salin selepas log masuk

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  
Salin selepas log masuk

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  
Salin selepas log masuk

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:

Aspek teknikal Fungsi CSS Bingkai kunci JavaScript
Panjang kod Secara amnya lebih pendek, menggunakan pembolehubah dan fungsi Boleh panjang bergantung pada bilangan bingkai utama dan titik interpolasi yang ditakrifkan Panjang bergantung pada faktor seperti elemen yang akan dimanipulasi, logik dan sifat yang akan digunakan.
Kemudahan pelaksanaan Mudah untuk corak dinamik dan berulang Mudah untuk animasi yang dipratentukan Pengendalian dan interaksi logik yang kompleks
Prestasi Prestasi tinggi, diturunkan kepada GPU dan kurang intensif CPU Prestasi tinggi, dimuatkan ke GPU, kurang intensif CPU Boleh kurang berprestasi, bergantung pada enjin JavaScript dan jumlah JavaScript yang akan dilaksanakan di web
Kawal Dinamik dan fleksibel Bingkai statik, pratakrif Sangat dinamik dan interaktif
Penyelenggaraan Sintaks ringkas dan mudah diselenggara Mudah diselenggara tetapi boleh mendapat verbose Boleh menjadi kompleks dan lebih sukar untuk dikekalkan, dan membuat perubahan pada logik
Jenis animasi Terbaik untuk animasi ringkas, berulang, matematik Sesuai untuk animasi terperinci berbilang langkah Terbaik untuk animasi interaktif dan responsif
Kebolehgunaan semula Kebolehgunaan semula yang tinggi dengan pembolehubah CSS kerana fungsi matematik boleh mencipta nilai yang berbeza untuk pembolehubah yang sama Sederhana, memerlukan pendua untuk animasi yang berbeza Kebolehgunaan semula yang tinggi dengan fungsi dan logik
Keserasian pelayar `Mod()` dan `Round()` tidak serasi dengan penyemak imbas Opera dan Samsung, selebihnya baik-baik saja Bingkai kunci telah wujud sejak sekian lama, jadi ia akan serasi untuk animasi berasaskan masa JavaScript serasi dengan semua pelayar untuk animasi berasaskan masa

Daripada perkara di atas, kita dapat melihat bahawa fungsi CSS apabila digunakan untuk animasi cemerlang dalam kesederhanaan, kebolehgunaan semula kod, kawalan dan prestasi berbanding dengan pelaksanaan lain.

Kesimpulan

Semasa artikel itu, kami membincangkan animasi berasaskan masa daripada mod(), hingga bulat() dan kemudian fungsi Trigonometrik.

Kami juga membandingkan fungsi ini dengan bingkai utama dan Javascript, dan kami telah dapat melihat bahawa animasi berasaskan masa berkembang kebanyakannya daripada kesederhanaan, kebolehgunaan semula yang dipertingkatkan dan pengoptimuman prestasi kerana ia ringan dan kurang berkemungkinan memberi kesan kepada prestasi berbanding animasi yang kompleks.

Ini, seterusnya, membantu meningkatkan pengalaman pengguna. Teruskan meneroka fungsi ini, dan teruskan pengekodan!!


Adakah bahagian hadapan anda memonopoli CPU pengguna anda?

Memandangkan bahagian hadapan web semakin kompleks, ciri tamak sumber menuntut lebih banyak lagi daripada penyemak imbas. Jika anda berminat untuk memantau dan menjejaki penggunaan CPU pihak pelanggan, penggunaan memori dan banyak lagi untuk semua pengguna anda dalam pengeluaran, cuba LogRocket.

Optimizing CSS time-based animations with new CSS functions

LogRocket adalah seperti DVR untuk apl web dan mudah alih, merakam semua yang berlaku dalam apl web, apl mudah alih atau tapak web anda. Daripada meneka sebab masalah berlaku, anda boleh mengagregat dan melaporkan metrik prestasi bahagian hadapan utama, memainkan semula sesi pengguna bersama-sama dengan keadaan aplikasi, log permintaan rangkaian dan secara automatik memaparkan semua ralat.

Modenkan cara anda menyahpepijat web dan apl mudah alih — mula memantau secara percuma.

Atas ialah kandungan terperinci Mengoptimumkan animasi berasaskan masa CSS dengan fungsi CSS baharu. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!