From 4b2cfda1c2e5f7719c0cda273775c3db446bb831 Mon Sep 17 00:00:00 2001 From: thednp Date: Mon, 23 Jan 2017 15:55:12 +0200 Subject: [PATCH] Minor documentation fixes: * Documentation updates * Fixed navigation on IE8 --- demo/about.html | 366 ++++++++----- demo/api.html | 534 +++++++++--------- demo/assets/js/minifill.js | 714 +++++++++++++------------ demo/assets/js/scripts.js | 45 +- demo/attr.html | 279 +++++----- demo/css.html | 354 ++++++------ demo/easing.html | 611 +++++++++++---------- demo/examples.html | 1040 ++++++++++++++++++------------------ demo/extend.html | 345 ++++++------ demo/features.html | 376 +++++++------ demo/index.html | 449 ++++++++-------- demo/options.html | 296 +++++----- demo/performance.html | 188 ++++--- demo/properties.html | 452 +++++++++------- demo/start.html | 220 ++++---- demo/svg.html | 731 +++++++++++++------------ demo/text.html | 285 +++++----- 17 files changed, 3871 insertions(+), 3414 deletions(-) diff --git a/demo/about.html b/demo/about.html index abe5ee5..2fe226f 100644 --- a/demo/about.html +++ b/demo/about.html @@ -3,7 +3,9 @@ - + + + @@ -12,170 +14,238 @@ - + + About KUTE.js | Javascript Animation Engine - + - + - + - + - + + + + + -
- -
- - +
+ +
+ +

Did you know?

+

Tween is a term used by animators and software engineers to define the numeric start, end and the inbetween values used in digital animation, + while the digital animation uses these tween values on a given frequency (interval) or scaled by hardware capability (monitors refresh rate, GPU vertical sync, etc). The term was introduced to the world of web development by early Javascrpt + libraries and later used in dedicated animation libraries such as GSAP, Dynamics, Velocity, + Shifty, our own KUTE.js here and many others. When used as a verb, it actually reffers to the interpolation of the values.

+

Tween Object is a Javascript Object that stores temporarily or for a given time a set of variables + such as tween values, HTML elements to animate, CSS properties and other tween options to be used for animation. To improve performance on repetitive animations, this object can be cached and reused whenever needed. In Javascript animation, + the term tween actually refers to the tween object.

+

polyfill is a term introduced by Remy Sharp back in 2009 as "a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively". Basically a polyfill covers what + legacy browsers don't support or in other cases corrects the implemented behavior that is different from the standards. More details.

+

requestAnimationFrame is a Javascript method developed to enable hardware acceleration animations for the + web today. In Javascript, the window.requestAnimationFrame(callback); method is all we need to setup animations really for all the above mentioned animation engines. Some developers built a polyfil to cover the legacy browsers chaos.

+

JANK is a term used when browsers miss frames due to long script execution and/or long layout recomposition. JANK is the phenomenon reffering to severe frame drops. Luckily there are people who + explain all about it, so you don't have to stay in the dark.

+

Methods are functions that create tween objects or control the animation for KUTE.js, so we will encounter mostly main methods and tween control methods. Once a main method is used, then + the control methods apply in a specific order.

+ + +

How Does It Work?

+

Well, first things first: it's smart built. Let's briefly explain the phases:

+
    +
  1. On first initialization KUTE.js creates some variables such as supported properties and their default values, the user's browser prefix, the true scroll container (some browsers actually scroll the body, while others prefer the HTML tag), + a boolean variable that makes KUTE.js aware it's working with IE8, as well as other variables required during the main thread. This phase is very important for the performance on the next phases.
  2. +
  3. In the next phase it's going to build the tween object with the chosen method according to it's distinct functionalities. If the chosen method is .to() KUTE.js will look for the current values of the properties used or assign + the default values built in the previous phase. For both methods, KUTE.js collects all the data, processes values and options (for instance easing functions need to be processed if you use a string like 'easingElasticOut', right?) + and builds the tween object, with all properties' values start and values end, measurement units, tween options and callback functions.
  4. +
  5. In the third phase KUTE.js is ready to start the animation, but the animation starts only after the .start() function, if used, has finished. When animation starts, KUTE.js will start ticking on the frequency decided + by requestAnimationFrame or setInterval for legacy browsers, quickly updating the style for the properties and execute the update:function callback if any. Also while animating, KUTE.js will begin + listening for your tween control input such as .pause() or .stop() or any other. Also, when a certain tween control method is used, KUTE.js will execute it's specific callback, if used.
  6. +
  7. When tween animation is finished, the complete:function callback function is executed and then KUTE.js starts the animation for any chained tween, or else will stop ticking with cancelAnimationFrame to save power.
  8. +
+

Basically, this is it!

+ +

A Note On Performance

+

As said before, performance varies from case to case; this chapter aims to explain what you should expect working with animation engines in these various scenarios at maximum stress, usually when your CPU cooler starts to work really hard, + and how scalable performance can really be on various machines, operating systems or mobile devices. We'll dig into each case, by property type or anything that can be considered a factor of influence.

+ +

Function Nesting

+

This could be one of the most important factors that influence performance, because we neglect this fact most of the time and changing the scope of an animation engine is important to look after. A quick example would be when we create tween + objects on events such as click, scroll or resize, we basically set a totally different scope for the animation and we fill the memory with large chunks of trash/jank, especially on events like resize.

+

A better way to handle this is to create the tween objects outside the event handlers and only start the animation with these handlers when certain conditions are met. EG: if (window.clientWidth > 760) { myTween.start() }. Also + keep in mind that this approach will eliminate any possible syncronization issues, but creating many animations is a huge temptation and this will create lots of problems for the old browsers, so keep the function nesting to as minimal + as possible as a general rule.

+ +

Translate and Position

+

While the code execution is the fastest for the layout modifiers or what we call box-model, say the position based properties set such as left or top, they may force + the entire page layout to change if not absolutelly positioned and thus requires the browser to repaint all elements affected by animated repositioning and their parent elements. On the other side translate doesn't trigger + a repaint but involves more complex operations such as more object traversing, string concatenation or check for certain conditions to be met. All of this is because translate is part of transform CSS3 property + that has to stack in a single line many more properties such as rotate, skew and scale. An article by Paul Irish explains more about differences in performance between position and translation.

+

Also any transform property is sub-pixel enabled and requires one or more decimals for accurate and smooth animation, decreasing overall performance. That said and with the emerging high resolution displays, it's safe to speculate that at + least translation could be optimized by rounding the values, while scale, rotation and skew requires three decimals.

+ +

To put it short left executes faster but requires repaint on every frame while translateX or translate3d execute slower but require no repaint on each animation + frame. The winner is left, when it comes to code execution speed, but if we also count the elements' size, the larger size the more favor the translation so the overall winner is translate. + The more pixels to recompose in the layout, the more time spent on each frame, and this is why translation is better in most cases, and animated positioning is best to be used as fallback animation for legacy browsers.

+ +

Translate, TranslateX and Translate3D

+

While running a 2D translate:150 animation could score similar performance as translateX:150, interestingly, translate3d:[150,0,0] is slightly faster than the other translations. Some performance tests confirm that translate3d is the prefered property for hardware acceleration. For this reason, translate3d is the winner and KUTE.js always uses it even if you only use translateX or + translateY for instance. +

+

Similarly, if you animate the 2D translate this always goes translate(x,y) even if you use translate:150 (only for the X axis) or translate:[150,0] (both X and Y axis), for better + performance as well. And by the way, this works great on IE9 and other legacy browsers.

+ +

Box Model

+

We compared position with transition above, but now we are going to talk about other issues related to resizers: width, height, margin, + padding and borderWidth or any of their variations. The code execution is super fast, but when resizing the window while animations are running, the browser is also computing the resize handlers, the animation + performance is very very low on all browsers, especially when you animate these resize properties. When this toxic combination occurs animating a large amount of elements could crash any browser, + no exception, and I think any developer should know about this.

+

The resize event triggered by these resizer properties can cause some severe issues with legacy browsers such as IE8. These good old browsers don't understand much about Javascript driven layout changes + and thus skip/fail to execute any handlers attached to window resize event bubbles.

+

A workaound for the resizers' effect on the layout would be to use them only for absolute positioned elements, this way the layout will not need to be repainted and the recomposition is limited to the elements themselves. If not, and + you are required to provide legacy support, you must DISABLE any resize handlers for IE8 and any other browser that runs slow or crashes. You should also consider not using any resize animation for legacy browsers especially when + usability and larger reach is expected.

+ +

RGB and HEX

+

When animating any color property such as (text) color or background-color, KUTE.js always uses/converts to RGB/RGBA, but there is a keepHex:true tween option that overrides that. Still some browsers such as Chrome will still show you the computed style for your color as RGB no matter what. The conversion process will decrease performance, making RGB the winner.

+ +

TO and FROMTO

+

The two main methods for creating animation setups (tween objects) that are coming with KUTE.js are .to() and .fromTo(). While .to() is much more simple and convenient to use, very useful for + tween chaining, it has to process the starting values on every .start() delaying the animation for a few miliseconds depending on the browser and hardware, making .fromTo() the winner. On + a large amount of elements animating at the same time, these scripting based delays can produce some serious syncronization issues, so caution is advised. In that case you should use .fromTo() properly.

+ +

Easing Functions

+

KUTE.js comes with 3 packs of easing functions: the popular easing functions by Robert Penner, dynamics physics easing + functions by Michael Villar and bezier-easing by Gaëtan Renaudeau. I've worked very hard to optimize the last 2 as much as possible, but they will never beat Robert + Penner's functions in any performance test, that's an all time winner.

+

The point here is that the more accuracy a function offers, the more power needed, and the result is less performance. For instance the cubic-bezier based functions have a 0.0000001 + error margin, while the Exponential easing functions by Robert Penner are somewhat glitchy on long page scrolls or translations. Interestingly, some physics based functions perform exceedingly well, and generally the + difference in performance is fairly negligible even for large amounts of elements, and have no impact on very few elements.

+ +

Garbage Collection

+

The goal of the development strategy is to be able to execute the script, update layout and repaint, all under 16 miliseconds, so that the animation runs constantly at 60fps. However running some + repeatable animations for a large amount of elements would really give garbage collectors a lot of work and thus some frames take more than 16 miliseconds. The more properties and/or elements, the more work.

+

While garbage collection is a great way modern browsers use to clean the memory, sometimes the garbage collector can jump in anytime, cousing drops in the order of miliseconds. Still, if it's the case, there are ways to help composing + the layout faster, but we will see that in the performance testing page.

+ +

Property Value Complexity

+

Just like the high amount of simultaneous animations influence performance, the property value complexity is also an important factor. If we were to compare all the supported properties in terms of complexity, the list would go like + this (from most expensive to least): path morphing, regular transform, matrix3d (not yet supported), box-shadow / text-shadow, colors, box model*, unitless props (scroll, opacity).

+

The * wants to emphasize the fact that box model properties of type resizers have additional performance drawbacks as discussed in a previous chapter.

+ +

OSs, Desktops and Mobiles

+

The performance tests have been performed mainly on Microsoft Windows 8.1 and Ubuntu Linux 14.04 Trusty Tahr with latest nVidia graphics drivers on both OSs, all set up for maximum performance. + The browsers are obviously Firefox (both OSs), Google Chrome (both OSs), Opera (both OSs) and IE11 (Win8).

+

The results show Windows based browsers came better than Ubuntu based ones, mainly because of DirectX and better drivers that greatly improve hardware accelerated graphics, + while Linux still faces some noticeable issues with vertical sync among many others, but hey it's a work in progress and it's open source!

+ +

The browsers' performance goes like this (from best to poorest): Google Chrome, Opera, Internet Explorer, Firefox. Yes, Firefox is the slowest on Windows OS. I never tested + anything on iOS or MAC-OS but I believe Safari performs very well with transforms. Some argue that + Safari outperforms Google Chrome due to the latest Webkit upgrade.

+ +

Also know that legacy browsers don't support requestAnimationFrame and pollyfills usually replace it with setInterval, a clasic Javascript method that's + significantly affecting performance, because it's one of the main causes for lots of JANK.

+ +

Another important aspect as far as performance goes, the power saving profiles on Windows OS drops performance for desktop computers and especally laptops. Also when a laptop is unplugged, Windows automatically changes power profile + drastically decreasing performance.

+ +

As for the mobiles, you must know that even if you have an octacore CPU powered phone or tablet is never going to match a desktop and not even a laptop. For a mobile device these guys recommend to keep everything under 7 miliseconds for the smooth experience that most users expect and that the animation performance of a phone is actually up to 5 times lower than a desktop or laptop. I would stress that having + 2 or 3 simoultaneous animations on a phone at a certain point is just about enough.

+ +

Another thing to keep in mind is that scrollling on a mobile device is actually hardware accelerated animation and thus compete for power drastically reducing performance for any + other CSS or Javascript driven animations. To understand how critical performance is on a mobile device, I highly recommend checking the Google I/O 2014 presentation. + Now you understand how much performance really matters.

+

Remember: do not open any Javascript animation engine performance test with your phone, you may burn your battery, espectially if it's unpluggable.

+ +

KUTE.js Project

+

KUTE.js continues what was started with jQueryTween (removed) and the main goal is to improve usability, compatibility, code quality and performance. KUTE.js includes a jQuery plugin to help you easily implement it + in your jQuery applications, and also packs a set of tools such as bezier and physics based easing functions, all elegantly packed for convenience and distributed via CDN.

+

It all started with a fork of the popular tween.js and ended up having a KUTE.js version 0.9.5 that's very fast, memory efficient and super easy to use.

+

In the hystory of the making there were consistent contributions of Dav aka @dalisoft for features such as play & pause, Text Plugin, as well as + for performance related issues. Generally I would stress that the code is a joint work of me and Dav. Big thanks Dav, well done.

+

Also I would like to thank Ingwie Phoenix for the npm/Bower and UMD implementations.

+ + +
+ + + + - -
- -

Did you know?

-

Tween is a term used by animators and software engineers to define the numeric start, end and the inbetween values used in digital animation, while the digital animation uses these tween values on a given frequency (interval) or scaled by hardware capability (monitors refresh rate, GPU vertical sync, etc). The term was introduced to the world of web development by early Javascrpt libraries and later used in dedicated animation libraries such as GSAP, Dynamics, Velocity, Shifty, our own KUTE.js here and many others. When used as a verb, it actually reffers to the interpolation of the values.

-

Tween Object is a Javascript Object that stores temporarily or for a given time a set of variables such as tween values, HTML elements to animate, CSS properties and other tween options to be used for animation. To improve performance on repetitive animations, this object can be cached and reused whenever needed. In Javascript animation, the term tween actually refers to the tween object.

-

polyfill is a term introduced by Remy Sharp back in 2009 as "a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively". Basically a polyfill covers what legacy browsers don't support or in other cases corrects the implemented behavior that is different from the standards. More details.

-

requestAnimationFrame is a Javascript method developed to enable hardware acceleration animations for the web today. In Javascript, the window.requestAnimationFrame(callback); method is all we need to setup animations really for all the above mentioned animation engines. Some developers built a polyfil to cover the legacy browsers chaos.

-

JANK is a term used when browsers miss frames due to long script execution and/or long layout recomposition. JANK is the phenomenon reffering to severe frame drops. Luckily there are people who explain all about it, so you don't have to stay in the dark.

-

Methods are functions that create tween objects or control the animation for KUTE.js, so we will encounter mostly main methods and tween control methods. Once a main method is used, then the control methods apply in a specific order.

- - -

How Does It Work?

-

Well, first things first: it's smart built. Let's briefly explain the phases:

-
    -
  1. On first initialization KUTE.js creates some variables such as supported properties and their default values, the user's browser prefix, the true scroll container (some browsers actually scroll the body, while others prefer the HTML tag), a boolean variable that makes KUTE.js aware it's working with IE8, as well as other variables required during the main thread. This phase is very important for the performance on the next phases.
  2. -
  3. In the next phase it's going to build the tween object with the chosen method according to it's distinct functionalities. If the chosen method is .to() KUTE.js will look for the current values of the properties used or assign the default values built in the previous phase. For both methods, KUTE.js collects all the data, processes values and options (for instance easing functions need to be processed if you use a string like 'easingElasticOut', right?) and builds the tween object, with all properties' values start and values end, measurement units, tween options and callback functions.
  4. -
  5. In the third phase KUTE.js is ready to start the animation, but the animation starts only after the .start() function, if used, has finished. When animation starts, KUTE.js will start ticking on the frequency decided by requestAnimationFrame or setInterval for legacy browsers, quickly updating the style for the properties and execute the update:function callback if any. Also while animating, KUTE.js will begin listening for your tween control input such as .pause() or .stop() or any other. Also, when a certain tween control method is used, KUTE.js will execute it's specific callback, if used.
  6. -
  7. When tween animation is finished, the complete:function callback function is executed and then KUTE.js starts the animation for any chained tween, or else will stop ticking with cancelAnimationFrame to save power.
  8. -
-

Basically, this is it!

- -

A Note On Performance

-

As said before, performance varies from case to case; this chapter aims to explain what you should expect working with animation engines in these various scenarios at maximum stress, usually when your CPU cooler starts to work really hard, and how scalable performance can really be on various machines, operating systems or mobile devices. We'll dig into each case, by property type or anything that can be considered a factor of influence.

- -

Function Nesting

-

This could be one of the most important factors that influence performance, because we neglect this fact most of the time and changing the scope of an animation engine is important to look after. A quick example would be when we create tween objects on events such as click, scroll or resize, we basically set a totally different scope for the animation and we fill the memory with large chunks of trash/jank, especially on events like resize.

-

A better way to handle this is to create the tween objects outside the event handlers and only start the animation with these handlers when certain conditions are met. EG: if (window.clientWidth > 760) { myTween.start() }. Also keep in mind that this approach will eliminate any possible syncronization issues, but creating many animations is a huge temptation and this will create lots of problems for the old browsers, so keep the function nesting to as minimal as possible as a general rule.

- -

Translate and Position

-

While the code execution is the fastest for the layout modifiers or what we call box-model, say the position based properties set such as left or top, they may force the entire page layout to change if not absolutelly positioned and thus requires the browser to repaint all elements affected by animated repositioning and their parent elements. On the other side translate doesn't trigger a repaint but involves more complex operations such as more object traversing, string concatenation or check for certain conditions to be met. All of this is because translate is part of transform CSS3 property that has to stack in a single line many more properties such as rotate, skew and scale. An article by Paul Irish explains more about differences in performance between position and translation.

-

Also any transform property is sub-pixel enabled and requires one or more decimals for accurate and smooth animation, decreasing overall performance. That said and with the emerging high resolution displays, it's safe to speculate that at least translation could be optimized by rounding the values, while scale, rotation and skew requires three decimals.

- -

To put it short left executes faster but requires repaint on every frame while translateX or translate3d execute slower but require no repaint on each animation frame. The winner is left, when it comes to code execution speed, but if we also count the elements' size, the larger size the more favor the translation so the overall winner is translate. The more pixels to recompose in the layout, the more time spent on each frame, and this is why translation is better in most cases, and animated positioning is best to be used as fallback animation for legacy browsers.

- -

Translate, TranslateX and Translate3D

-

While running a 2D translate:150 animation could score similar performance as translateX:150, interestingly, translate3d:[150,0,0] is slightly faster than the other translations. Some performance tests confirm that translate3d is the prefered property for hardware acceleration. For this reason, translate3d is the winner and KUTE.js always uses it even if you only use translateX or translateY for instance.

-

Similarly, if you animate the 2D translate this always goes translate(x,y) even if you use translate:150 (only for the X axis) or translate:[150,0] (both X and Y axis), for better performance as well. And by the way, this works great on IE9 and other legacy browsers.

- -

Box Model

-

We compared position with transition above, but now we are going to talk about other issues related to resizers: width, height, margin, padding and borderWidth or any of their variations. The code execution is super fast, but when resizing the window while animations are running, the browser is also computing the resize handlers, the animation performance is very very low on all browsers, especially when you animate these resize properties. When this toxic combination occurs animating a large amount of elements could crash any browser, no exception, and I think any developer should know about this.

-

The resize event triggered by these resizer properties can cause some severe issues with legacy browsers such as IE8. These good old browsers don't understand much about Javascript driven layout changes and thus skip/fail to execute any handlers attached to window resize event bubbles.

-

A workaound for the resizers' effect on the layout would be to use them only for absolute positioned elements, this way the layout will not need to be repainted and the recomposition is limited to the elements themselves. If not, and you are required to provide legacy support, you must DISABLE any resize handlers for IE8 and any other browser that runs slow or crashes. You should also consider not using any resize animation for legacy browsers especially when usability and larger reach is expected.

- -

RGB and HEX

-

When animating any color property such as (text) color or background-color, KUTE.js always uses/converts to RGB/RGBA, but there is a keepHex:true tween option that overrides that. Still some browsers such as Chrome will still show you the computed style for your color as RGB no matter what. The conversion process will decrease performance, making RGB the winner.

- -

TO and FROMTO

-

The two main methods for creating animation setups (tween objects) that are coming with KUTE.js are .to() and .fromTo(). While .to() is much more simple and convenient to use, very useful for tween chaining, it has to process the starting values on every .start() delaying the animation for a few miliseconds depending on the browser and hardware, making .fromTo() the winner. On a large amount of elements animating at the same time, these scripting based delays can produce some serious syncronization issues, so caution is advised. In that case you should use .fromTo() properly.

- -

Easing Functions

-

KUTE.js comes with 3 packs of easing functions: the popular easing functions by Robert Penner, dynamics physics easing functions by Michael Villar and bezier-easing by Gaëtan Renaudeau. I've worked very hard to optimize the last 2 as much as possible, but they will never beat Robert Penner's functions in any performance test, that's an all time winner.

-

The point here is that the more accuracy a function offers, the more power needed, and the result is less performance. For instance the cubic-bezier based functions have a 0.0000001 error margin, while the Exponential easing functions by Robert Penner are somewhat glitchy on long page scrolls or translations. Interestingly, some physics based functions perform exceedingly well, and generally the difference in performance is fairly negligible even for large amounts of elements, and have no impact on very few elements.

- -

Garbage Collection

-

The goal of the development strategy is to be able to execute the script, update layout and repaint, all under 16 miliseconds, so that the animation runs constantly at 60fps. However running some repeatable animations for a large amount of elements would really give garbage collectors a lot of work and thus some frames take more than 16 miliseconds. The more properties and/or elements, the more work.

-

While garbage collection is a great way modern browsers use to clean the memory, sometimes the garbage collector can jump in anytime, cousing drops in the order of miliseconds. Still, if it's the case, there are ways to help composing the layout faster, but we will see that in the performance testing page.

- -

Property Value Complexity

-

Just like the high amount of simultaneous animations influence performance, the property value complexity is also an important factor. If we were to compare all the supported properties in terms of complexity, the list would go like this (from most expensive to least): path morphing, regular transform, matrix3d (not yet supported), box-shadow / text-shadow, colors, box model*, unitless props (scroll, opacity).

-

The * wants to emphasize the fact that box model properties of type resizers have additional performance drawbacks as discussed in a previous chapter.

- -

OSs, Desktops and Mobiles

-

The performance tests have been performed mainly on Microsoft Windows 8.1 and Ubuntu Linux 14.04 Trusty Tahr with latest nVidia graphics drivers on both OSs, all set up for maximum performance. The browsers are obviously Firefox (both OSs), Google Chrome (both OSs), Opera (both OSs) and IE11 (Win8).

-

The results show Windows based browsers came better than Ubuntu based ones, mainly because of DirectX and better drivers that greatly improve hardware accelerated graphics, while Linux still faces some noticeable issues with vertical sync among many others, but hey it's a work in progress and it's open source!

- -

The browsers' performance goes like this (from best to poorest): Google Chrome, Opera, Internet Explorer, Firefox. Yes, Firefox is the slowest on Windows OS. I never tested anything on iOS or MAC-OS but I believe Safari performs very well with transforms. Some argue that Safari outperforms Google Chrome due to the latest Webkit upgrade.

- -

Also know that legacy browsers don't support requestAnimationFrame and pollyfills usually replace it with setInterval, a clasic Javascript method that's significantly affecting performance, because it's one of the main causes for lots of JANK.

- -

Another important aspect as far as performance goes, the power saving profiles on Windows OS drops performance for desktop computers and especally laptops. Also when a laptop is unplugged, Windows automatically changes power profile drastically decreasing performance.

- -

As for the mobiles, you must know that even if you have an octacore CPU powered phone or tablet is never going to match a desktop and not even a laptop. For a mobile device these guys recommend to keep everything under 7 miliseconds for the smooth experience that most users expect and that the animation performance of a phone is actually up to 5 times lower than a desktop or laptop. I would stress that having 2 or 3 simoultaneous animations on a phone at a certain point is just about enough.

- -

Another thing to keep in mind is that scrollling on a mobile device is actually hardware accelerated animation and thus compete for power drastically reducing performance for any other CSS or Javascript driven animations. To understand how critical performance is on a mobile device, I highly recommend checking the Google I/O 2014 presentation. Now you understand how much performance really matters.

-

Remember: do not open any Javascript animation engine performance test with your phone, you may burn your battery, espectially if it's unpluggable.

- -

KUTE.js Project

-

KUTE.js continues what was started with jQueryTween (removed) and the main goal is to improve usability, compatibility, code quality and performance. KUTE.js includes a jQuery plugin to help you easily implement it in your jQuery applications, and also packs a set of tools such as bezier and physics based easing functions, all elegantly packed for convenience and distributed via CDN.

-

It all started with a fork of the popular tween.js and ended up having a KUTE.js version 0.9.5 that's very fast, memory efficient and super easy to use.

-

In the hystory of the making there were consistent contributions of Dav aka @dalisoft for features such as play & pause, Text Plugin, as well as for performance related issues. Generally I would stress that the code is a joint work of me and Dav. Big thanks Dav, well done.

-

Also I would like to thank Ingwie Phoenix for the npm/Bower and UMD implementations.

- - -
- - - - - - + - - - - + + + + + + diff --git a/demo/api.html b/demo/api.html index 8518d8c..d930791 100644 --- a/demo/api.html +++ b/demo/api.html @@ -1,259 +1,275 @@ - - - - - - - - - - - - - - - - - KUTE.js Developer API | Javascript Animation Engine - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
-

Public Methods

-

These methods allow you to create tween objects and collections of tween objects; as we know, a tween object is essentially like an animation setup for a given HTML element, defining CSS properties, animation duration, repeat or other options. The methods have different uses and performance scores while making it easy to work with.

- -

Single Tween Object

-

As the heading suggests, the following two methods allow you to create tween objects for individual HTML elements, except when used in combination with jQuery and the KUTE.js plugin for jQuery, where, as jQuery always does, it always works with collections of elements.

-

.to() method is the most simple method which allows you to create tween objects for animating CSS properties from a specific default value OR from current/computed value TO a desired value. - It's performance is not the same as for the .fromTo() method as it has to compute the default/current value on tween .start() and thus delays the animation for a couple of miliseconds; still this feature is great for simple animations AND it has the ability to stack transform properties as they go, making smooth transform animations on chained tweens. See the .start() method for the solution for sync/delay issue.

-

Considering a given div element is already transparent, a super quick example would be:

-
KUTE.to(div,{opacity:1}).start()
-

As you might have guessed, this method is useful for creating simple animations such as for scroll, hide/reveal elements, or generally when you don't know the current value of the property you are trying to animate.

-

.fromTo() method is the best way to build animations for BEST performance and absolute control. The tests prove this method to be the fastest method but unlike the .to() method, it does not stack transform properties on chained tweens. Along with the performance advantage, you can set measurement units for both starting and end values, to avoid glitches. We've talked about this in the features page. Here's a quick example:

-
KUTE.fromTo(div,{opacity:1},{opacity:0}).start()
- -

Tween Object Collections

-

The two new methods allow you to create animations for multiple HTML elements at the same time, all in a single line of code. They use the above methods to create a tween object for each element of the collection and also enable the tween control methods in this new context.

-

.allTo() method allows you to create an array of tween objects for a collection of elements. This method is using the above .to() method and inherits it's functionality. Considering a given collection myDivs elements, a nice example would be:

-
// on the fly, grab the elements by className,
-// do the tween objects array, and start kicking
-KUTE.allTo( '.my-div-class', {opacity:1}, {offset: 200, duration: 500} ).start();
-
-// or we cache the objects for better performance and / or later control
-var myDivs          = document.querySelectorAll('.my-div-class');
-var myDivsTweens    = KUTE.allTo( myDivs, {opacity:1}, {offset: 200, duration: 500} );
-
- -

.allFromTo() method is also a method to animate a collection of elements and it uses the .fromTo() method. Quick example:

-
KUTE.allFromTo( myDivs, {opacity:1}, {opacity:0}, {offset: 200, duration: 500} ).start()
- -

As you can see the above code, these methods have a specific tween option called offset that allows you to set a delay in miliseconds between the starting time of each tween animation. Most tween control methods apply to both methods, except for the .chain() method. In order to chain another tween to one of the myDivsTweens objects, we would need to access it from the array, but let's leave that for later.

-
- -
-

Tween Control Methods

-

These methods allows you to control when the animation starts or stops. Let's write a basic tween object to work with the methods:

-
var tween = KUTE.fromTo(div,{opacity:1},{opacity:0});
-

This tween object is now ready to work with the methods.

- -

Starting Animations

-

.start() method starts animation for a given tween object. It can start the animation for both cached and non-cached objects. Unlike previous versions of KUTE.js, where animation started immediately after tween object creation, now you have to manually start them. This method also applies to arrays of tween objects created with .allTo() and .allFromTo() methods.

-
//cached object defined above
-tween.start();
-
-// non-cached object are created on the fly and garbage collected after animation has finised
-KUTE.fromTo(div,{opacity:1},{opacity:0}).start();
-
-// also start the tween at a certain time
-tween.start(now); // where now must be the current or future time as number, see below
-
-// lastly the method works with tweens made with .allTo() and .allFromTo() methods
-KUTE.allFromTo(divs,{opacity:1},{opacity:0}).start();
-KUTE.allTo(divs,{opacity:0}).start();
-
- -

As you can see, you can also set a time for the animation to start, example: tween.start(myTimeValue). Having access to the method is useful when starting animation for large amounts of elements with same properties at the same time because using it properly eliminates any syncronization issue that may occur on animations start, even if you are using the .to() method. The trick is super duper simple:

- -
// step 1 - create an empty array and grab the elements to animate
-var tweens = [], myElements = document.querySelector('.myManyElements'), numberOfElements = myElements.length;
-
-// step 2 - define tween objects for each element
-for (var i = 0; i < numberOfElements; i++) {
-	var tween = KUTE.fromTo(myElements[i], fromValues, toValues, options);
-	//now we populate the tweens array
-	tweens.push(tween);
-}
-
-// step 3 - calculate the right time to start
-// first we need the exact current time
-var now = window.performance.now(); // this returns the exact current time in numeric format
-
-// also we estimate/calculate an adjustment lag
-// depending on the number of the elements AND hardware capability
-// maybe (numberOfElements / 16) would be an accurate value for PCs
-var lag = 100; // number of miliseconds for the script to built tween objects for all elements
-
-// step4 - we just start the animation for all elements at once
-for (var i = 0; i < numberOfElements; i++) {
-	tweens[i].start(now+lag);
-}
-
- -

In other cases the new methods .allTo() and .allFromTo() can be more useful.

- -

Stopping Animation

-

.stop() method stops animation for a given tween object or an array of tween objects (built with .to()/.fromTo() methods) while animating. You cannot stop the animation for tween objects created on the fly, only for cached objects. Let's assume that for the given tween we decide to stop the animation via click action:

-
// for a tween object
-stopButton.addEventListener('click', function(){
-	myTween.stop(); // myMultiTweens.stop();
-}, false);
-
- -

Pausing Animation

-

.pause() method freezez the animation at any given time for a given tween object or collection, and unlike the .stop() method, this one allows resuming the animation on a later use of the next method .play().

-
pauseButton.addEventListener('click', function(){
-	tween.pause(); // or myMultiTweens.pause();
-}, false);
-
- -

Resuming Paused Animation

-

.play() or .resume() methods allows you to resume an animation for a given tween object or collection of tweens, only if it was paused or else will produce no effect.

-
playButton.addEventListener('click', function(){
-	tween.play(); // or tween.resume(); || or myMultiTweens.resume();
-}, false);
-
- -

Chaining Tweens

-

.chain() method can be used to chain tweens together. When the animation finishes for a given tween, it calls for .start() for another tween(s).

-
var tween2 = KUTE.fromTo(div,{left:50},{left:0});
-
-//the first tween chains the new tween
-tween.chain(tween2);
-
-//the new tween chains the first one creating a loop
-tween2.chain(tween);
-
- -

It's also possible to chain multiple tweens, just as shown in the below example.

-
//chain multiple tweens
-tween.chain(tween1,tween2);
-
- -

Another thing we talked before is the ability to chain to one of the tween object within the array built with .allTo() or .allFromTo() methods.

-
// chain to a tween from collection
-var tweensCollection = KUTE.allTo('.a-class-for-multiple-elements', {opacity: 1});
-
-// considering the collection has 5 tweens,
-// the array is right here tweensCollection.tweens, so
-// let's grab the second and chain another tween to it
-tweensCollection.tweens[1].chain(tween2);
-
-

Also we can chain the tweens created with .allTo() and .allFromTo() methods like this:

-
// chain a collection of tweens to another tween
-var tweensCollection2 = KUTE.allTo('.a-class-for-multiple-elements', {opacity: 1});
-
-// the array is right here tweensCollection2.tweens
-// we can pass it in the chain of another tween
-tween2.chain(tweensCollection2.tweens);
-
-
- -
- - - -
- - - - -
- - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + KUTE.js Developer API | Javascript Animation Engine + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+

Public Methods

+

These methods allow you to create tween objects and collections of tween objects; as we know, a tween object is essentially like an animation setup for a given HTML element, defining CSS properties, animation + duration, repeat or other options. The methods have different uses and performance scores while making it easy to work with.

+ +

Single Tween Object

+

As the heading suggests, the following two methods allow you to create tween objects for individual HTML elements, except when used in combination with jQuery and the KUTE.js plugin for jQuery, where, as jQuery always does, it always works + with collections of elements.

+

.to() method is the most simple method which allows you to create tween objects for animating CSS properties from a specific default value OR from current/computed value TO a desired value. It's performance is not the same as for + the .fromTo() method as it has to compute the default/current value on tween .start() and thus delays the animation for a couple of miliseconds; still this feature is great for simple animations AND it has + the ability to stack transform properties as they go, making smooth transform animations on chained tweens. See the .start() method for the solution for sync/delay issue.

+

Considering a given div element is already transparent, a super quick example would be:

+
KUTE.to(div,{opacity:1}).start()
+

As you might have guessed, this method is useful for creating simple animations such as for scroll, hide/reveal elements, or generally when you don't know the current value of the property you are trying to animate.

+

.fromTo() method is the best way to build animations for BEST performance and absolute control. The tests prove this method to be the fastest method but unlike the .to() method, it does not stack transform properties + on chained tweens. Along with the performance advantage, you can set measurement units for both starting and end values, to avoid glitches. We've talked about this in the features page. Here's a quick example:

+
KUTE.fromTo(div,{opacity:1},{opacity:0}).start()
+ +

Tween Object Collections

+

The two new methods allow you to create animations for multiple HTML elements at the same time, all in a single line of code. They use the above methods to create a tween object for each element of the collection and also enable the tween + control methods in this new context.

+

.allTo() method allows you to create an array of tween objects for a collection of elements. This method is using the above .to() method and inherits it's functionality. Considering a given collection myDivs elements, a nice example would be:

+
// on the fly, grab the elements by className,
+// do the tween objects array, and start kicking
+KUTE.allTo( '.my-div-class', {opacity:1}, {offset: 200, duration: 500} ).start();
+
+// or we cache the objects for better performance and / or later control
+var myDivs          = document.querySelectorAll('.my-div-class');
+var myDivsTweens    = KUTE.allTo( myDivs, {opacity:1}, {offset: 200, duration: 500} );
+
+ +

.allFromTo() method is also a method to animate a collection of elements and it uses the .fromTo() method. Quick example:

+
KUTE.allFromTo( myDivs, {opacity:1}, {opacity:0}, {offset: 200, duration: 500} ).start()
+ +

As you can see the above code, these methods have a specific tween option called offset that allows you to set a delay in miliseconds between the starting time of each tween animation. Most tween control methods apply to both + methods, except for the .chain() method. In order to chain another tween to one of the myDivsTweens objects, we would need to access it from the array, but let's leave that for later.

+
+ +
+

Tween Control Methods

+

These methods allows you to control when the animation starts or stops. Let's write a basic tween object to work with the methods:

+
var tween = KUTE.fromTo(div,{opacity:1},{opacity:0});
+

This tween object is now ready to work with the methods.

+ +

Starting Animations

+

.start() method starts animation for a given tween object. It can start the animation for both cached and non-cached objects. Unlike previous versions of KUTE.js, where animation started immediately after tween object creation, + now you have to manually start them. This method also applies to arrays of tween objects created with .allTo() and .allFromTo() methods.

+
//cached object defined above
+tween.start();
+
+// non-cached object are created on the fly and garbage collected after animation has finised
+KUTE.fromTo(div,{opacity:1},{opacity:0}).start();
+
+// also start the tween at a certain time
+tween.start(now); // where now must be the current or future time as number, see below
+
+// lastly the method works with tweens made with .allTo() and .allFromTo() methods
+KUTE.allFromTo(divs,{opacity:1},{opacity:0}).start();
+KUTE.allTo(divs,{opacity:0}).start();
+
+ +

As you can see, you can also set a time for the animation to start, example: tween.start(myTimeValue). Having access to the method is useful when starting animation for large amounts of elements with same properties at the same + time because using it properly eliminates any syncronization issue that may occur on animations start, even if you are using the .to() method. The trick is super duper simple:

+ +
// step 1 - create an empty array and grab the elements to animate
+var tweens = [], myElements = document.querySelector('.myManyElements'), numberOfElements = myElements.length;
+
+// step 2 - define tween objects for each element
+for (var i = 0; i < numberOfElements; i++) {
+  var tween = KUTE.fromTo(myElements[i], fromValues, toValues, options);
+  //now we populate the tweens array
+  tweens.push(tween);
+}
+
+// step 3 - calculate the right time to start
+// first we need the exact current time
+var now = window.performance.now(); // this returns the exact current time in numeric format
+
+// also we estimate/calculate an adjustment lag
+// depending on the number of the elements AND hardware capability
+// maybe (numberOfElements / 16) would be an accurate value for PCs
+var lag = 100; // number of miliseconds for the script to built tween objects for all elements
+
+// step4 - we just start the animation for all elements at once
+for (var i = 0; i < numberOfElements; i++) {
+  tweens[i].start(now+lag);
+}
+
+ +

In other cases the new methods .allTo() and .allFromTo() can be more useful.

+ +

Stopping Animation

+

.stop() method stops animation for a given tween object or an array of tween objects (built with .to()/.fromTo() methods) while animating. You cannot stop the animation for tween objects created on the + fly, only for cached objects. Let's assume that for the given tween we decide to stop the animation via click action:

+
// for a tween object
+stopButton.addEventListener('click', function(){
+  myTween.stop(); // myMultiTweens.stop();
+}, false);
+
+ +

Pausing Animation

+

.pause() method freezez the animation at any given time for a given tween object or collection, and unlike the .stop() method, this one allows resuming the animation on a later use of the next method .play().

+
pauseButton.addEventListener('click', function(){
+  tween.pause(); // or myMultiTweens.pause();
+}, false);
+
+ +

Resuming Paused Animation

+

.play() or .resume() methods allows you to resume an animation for a given tween object or collection of tweens, only if it was paused or else will produce no effect.

+
playButton.addEventListener('click', function(){
+  tween.play(); // or tween.resume(); || or myMultiTweens.resume();
+}, false);
+
+ +

Chaining Tweens

+

.chain() method can be used to chain tweens together. When the animation finishes for a given tween, it calls for .start() for another tween(s).

+
var tween2 = KUTE.fromTo(div,{left:50},{left:0});
+
+//the first tween chains the new tween
+tween.chain(tween2);
+
+//the new tween chains the first one creating a loop
+tween2.chain(tween);
+
+ +

It's also possible to chain multiple tweens, just as shown in the below example.

+
//chain multiple tweens
+tween.chain(tween1,tween2);
+
+ +

Another thing we talked before is the ability to chain to one of the tween object within the array built with .allTo() or .allFromTo() methods.

+
// chain to a tween from collection
+var tweensCollection = KUTE.allTo('.a-class-for-multiple-elements', {opacity: 1});
+
+// considering the collection has 5 tweens,
+// the array is right here tweensCollection.tweens, so
+// let's grab the second and chain another tween to it
+tweensCollection.tweens[1].chain(tween2);
+
+

Also we can chain the tweens created with .allTo() and .allFromTo() methods like this:

+
// chain a collection of tweens to another tween
+var tweensCollection2 = KUTE.allTo('.a-class-for-multiple-elements', {opacity: 1});
+
+// the array is right here tweensCollection2.tweens
+// we can pass it in the chain of another tween
+tween2.chain(tweensCollection2.tweens);
+
+
+ +
+ + + +
+ + + + +
+ + + + + + + + + + + + + + + + + + + diff --git a/demo/assets/js/minifill.js b/demo/assets/js/minifill.js index 4300e4d..43d8d0e 100644 --- a/demo/assets/js/minifill.js +++ b/demo/assets/js/minifill.js @@ -1,348 +1,382 @@ -// Document -// HTMLDocument is an extension of Document. If the browser has HTMLDocument but not Document, the former will suffice as an alias for the latter. -if (!this.Document){this.Document = this.HTMLDocument; } - -// Element -if (!window.HTMLElement) { window.HTMLElement = window.Element; } - -// Window -(function(global) { - if (global.constructor) { - global.Window = global.constructor; - } else { - (global.Window = global.constructor = new Function('return function Window() {}')()).prototype = this; - } -}(this)); - -// Date.now -if(!Date.now){ Date.now = function now() { return new Date().getTime(); }; } - -// performance.now +// minifill.js | MIT | dnp_theme (function(){ - if ("performance" in window == false) { window.performance = {}; } - - if ("now" in window.performance == false){ - var nowOffset = Date.now(); - - window.performance.now = function now(){ - return Date.now() - nowOffset; - } - } -})(); + + // all repeated strings get a single reference + // document | window | element + corrections + var Doc = 'Document', doc = document, DOCUMENT = this[Doc] || this.HTMLDocument, // IE8 + WIN = 'Window', win = window, WINDOW = this.constructor || this[WIN] || Window, // old Safari + HTMLELEMENT = 'HTMLElement', documentElement = 'documentElement', ELEMENT = Element, + + // classList related + className = 'className', add = 'add', classList = 'classList', remove = 'remove', contains = 'contains', + + // object | array related + prototype = 'prototype', indexOf = 'indexOf', length = 'length', + + // performance + now = 'now', performance = 'performance', + + // getComputedStyle + getComputedStyle = 'getComputedStyle', currentStyle = 'currentStyle', fontSize = 'fontSize', + + // event related + EVENT = 'Event', CustomEvent = 'CustomEvent', IE8EVENTS = '_events', + etype = 'type', target = 'target', currentTarget = 'currentTarget', relatedTarget = 'relatedTarget', + cancelable = 'cancelable', bubbles = 'bubbles', cancelBubble = 'cancelBubble', cancelImmediate = 'cancelImmediate', detail = 'detail', + addEventListener = 'addEventListener', removeEventListener = 'removeEventListener', dispatchEvent = 'dispatchEvent'; + + + // Element + if (!win[HTMLELEMENT]) { win[HTMLELEMENT] = win[ELEMENT]; } + + // Array[prototype][indexOf] + if (!Array[prototype][indexOf]) { + Array[prototype][indexOf] = function(searchElement) { + if (this === undefined || this === null) { + throw new TypeError(this + ' is not an object'); + } + + var arraylike = this instanceof String ? this.split('') : this, + lengthValue = Math.max(Math.min(arraylike[length], 9007199254740991), 0) || 0, + index = Number(arguments[1]) || 0; + + index = (index < 0 ? Math.max(lengthValue + index, 0) : index) - 1; + + while (++index < lengthValue) { + if (index in arraylike && arraylike[index] === searchElement) { + return index; + } + } + + return -1; + }; + } + + // Date[now] + if(!Date[now]){ Date[now] = function() { return new Date().getTime(); }; } + + // performance[now] + (function(){ + if (performance in win == false) { win[performance] = {}; } + + if (now in win[performance] == false){ + var nowOffset = Date[now](); + + window[performance][now] = function(){ + return Date[now]() - nowOffset; + } + } + })(); -// Array.prototype.indexOf -if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function indexOf(searchElement) { - if (this === undefined || this === null) { - throw new TypeError(this + 'is not an object'); - } - - var arraylike = this instanceof String ? this.split('') : this, - length = Math.max(Math.min(arraylike.length, 9007199254740991), 0) || 0, - index = Number(arguments[1]) || 0; - - index = (index < 0 ? Math.max(length + index, 0) : index) - 1; - - while (++index < length) { - if (index in arraylike && arraylike[index] === searchElement) { - return index; - } - } - - return -1; - }; -} + // getComputedStyle + if (!(getComputedStyle in win)) { + function getComputedStylePixel(element, property, fontSizeValue) { + + // Internet Explorer sometimes struggles to read currentStyle until the element's document is accessed. + var value = element.document && element[currentStyle][property].match(/([\d\.]+)(%|cm|em|in|mm|pc|pt|)/) || [0, 0, ''], + size = value[1], + suffix = value[2], + rootSize; + + fontSizeValue = !fontSizeValue ? fontSizeValue : /%|em/.test(suffix) && element.parentElement ? getComputedStylePixel(element.parentElement, 'fontSize', null) : 16; + rootSize = property == 'fontSize' ? fontSizeValue : /width/i.test(property) ? element.clientWidth : element.clientHeight; + + return suffix == '%' ? size / 100 * rootSize : + suffix == 'cm' ? size * 0.3937 * 96 : + suffix == 'em' ? size * fontSizeValue : + suffix == 'in' ? size * 96 : + suffix == 'mm' ? size * 0.3937 * 96 / 10 : + suffix == 'pc' ? size * 12 * 96 / 72 : + suffix == 'pt' ? size * 96 / 72 : + size; + } + + function setShortStyleProperty(style, property) { + var borderSuffix = property == 'border' ? 'Width' : '', + t = property + 'Top' + borderSuffix, + r = property + 'Right' + borderSuffix, + b = property + 'Bottom' + borderSuffix, + l = property + 'Left' + borderSuffix; + + style[property] = (style[t] == style[r] && style[t] == style[b] && style[t] == style[l] ? [ style[t] ] : + style[t] == style[b] && style[l] == style[r] ? [ style[t], style[r] ] : + style[l] == style[r] ? [ style[t], style[r], style[b] ] : + [ style[t], style[r], style[b], style[l] ]).join(' '); + } + + // + function CSSStyleDeclaration(element) { + var style = this, + currentStyleValue = element[currentStyle], + fontSizeValue = getComputedStylePixel(element, fontSize), + unCamelCase = function (match) { + return '-' + match.toLowerCase(); + }, + property; + + for (property in currentStyleValue) { + Array.prototype.push.call(style, property == 'styleFloat' ? 'float' : property.replace(/[A-Z]/, unCamelCase)); + + if (property == 'width') { + style[property] = element.offsetWidth + 'px'; + } else if (property == 'height') { + style[property] = element.offsetHeight + 'px'; + } else if (property == 'styleFloat') { + style.float = currentStyleValue[property]; + } else if (/margin.|padding.|border.+W/.test(property) && style[property] != 'auto') { + style[property] = Math.round(getComputedStylePixel(element, property, fontSizeValue)) + 'px'; + } else if (/^outline/.test(property)) { + // errors on checking outline + try { + style[property] = currentStyleValue[property]; + } catch (error) { + style.outlineColor = currentStyleValue.color; + style.outlineStyle = style.outlineStyle || 'none'; + style.outlineWidth = style.outlineWidth || '0px'; + style.outline = [style.outlineColor, style.outlineWidth, style.outlineStyle].join(' '); + } + } else { + style[property] = currentStyleValue[property]; + } + } + + setShortStyleProperty(style, 'margin'); + setShortStyleProperty(style, 'padding'); + setShortStyleProperty(style, 'border'); + + style[fontSize] = Math.round(fontSizeValue) + 'px'; + } + + CSSStyleDeclaration[prototype] = { + constructor: CSSStyleDeclaration, + // .getPropertyPriority + getPropertyPriority: function () { + throw new Error('DOM Exception 9'); + }, + // .getPropertyValue + getPropertyValue: function (property) { + return this[property.replace(/-\w/g, function (match) { + return match[1].toUpperCase(); + })]; + }, + // .item + item: function (index) { + return this[index]; + }, + // .removeProperty + removeProperty: function () { + throw new Error('DOM Exception 7'); + }, + // .setProperty + setProperty: function () { + throw new Error('DOM Exception 7'); + }, + // .getPropertyCSSValue + getPropertyCSSValue: function () { + throw new Error('DOM Exception 9'); + } + }; + + // .getComputedStyle + win[getComputedStyle] = function(element) { + return new CSSStyleDeclaration(element); + }; + } -// getComputedStyle -if (!('getComputedStyle' in window)) { - (function(){ - function getComputedStylePixel(element, property, fontSize) { - - // Internet Explorer sometimes struggles to read currentStyle until the element's document is accessed. - var value = element.document && element.currentStyle[property].match(/([\d\.]+)(%|cm|em|in|mm|pc|pt|)/) || [0, 0, ''], - size = value[1], - suffix = value[2], - rootSize; - - fontSize = !fontSize ? fontSize : /%|em/.test(suffix) && element.parentElement ? getComputedStylePixel(element.parentElement, 'fontSize', null) : 16; - rootSize = property == 'fontSize' ? fontSize : /width/i.test(property) ? element.clientWidth : element.clientHeight; - - return suffix == '%' ? size / 100 * rootSize : - suffix == 'cm' ? size * 0.3937 * 96 : - suffix == 'em' ? size * fontSize : - suffix == 'in' ? size * 96 : - suffix == 'mm' ? size * 0.3937 * 96 / 10 : - suffix == 'pc' ? size * 12 * 96 / 72 : - suffix == 'pt' ? size * 96 / 72 : - size; - } - - function setShortStyleProperty(style, property) { - var borderSuffix = property == 'border' ? 'Width' : '', - t = property + 'Top' + borderSuffix, - r = property + 'Right' + borderSuffix, - b = property + 'Bottom' + borderSuffix, - l = property + 'Left' + borderSuffix; - - style[property] = (style[t] == style[r] && style[t] == style[b] && style[t] == style[l] ? [ style[t] ] : - style[t] == style[b] && style[l] == style[r] ? [ style[t], style[r] ] : - style[l] == style[r] ? [ style[t], style[r], style[b] ] : - [ style[t], style[r], style[b], style[l] ]).join(' '); - } - - // - function CSSStyleDeclaration(element) { - var style = this, - currentStyle = element.currentStyle, - fontSize = getComputedStylePixel(element, 'fontSize'), - unCamelCase = function (match) { - return '-' + match.toLowerCase(); - }, - property; - - for (property in currentStyle) { - Array.prototype.push.call(style, property == 'styleFloat' ? 'float' : property.replace(/[A-Z]/, unCamelCase)); - - if (property == 'width') { - style[property] = element.offsetWidth + 'px'; - } else if (property == 'height') { - style[property] = element.offsetHeight + 'px'; - } else if (property == 'styleFloat') { - style.float = currentStyle[property]; - } else if (/margin.|padding.|border.+W/.test(property) && style[property] != 'auto') { - style[property] = Math.round(getComputedStylePixel(element, property, fontSize)) + 'px'; - } else if (/^outline/.test(property)) { - // errors on checking outline - try { - style[property] = currentStyle[property]; - } catch (error) { - style.outlineColor = currentStyle.color; - style.outlineStyle = style.outlineStyle || 'none'; - style.outlineWidth = style.outlineWidth || '0px'; - style.outline = [style.outlineColor, style.outlineWidth, style.outlineStyle].join(' '); - } - } else { - style[property] = currentStyle[property]; - } - } - - setShortStyleProperty(style, 'margin'); - setShortStyleProperty(style, 'padding'); - setShortStyleProperty(style, 'border'); - - style.fontSize = Math.round(fontSize) + 'px'; - } - - CSSStyleDeclaration.prototype = { - constructor: CSSStyleDeclaration, - // .getPropertyPriority - getPropertyPriority: function () { - throw new Error('NotSupportedError: DOM Exception 9'); - }, - // .getPropertyValue - getPropertyValue: function (property) { - return this[property.replace(/-\w/g, function (match) { - return match[1].toUpperCase(); - })]; - }, - // .item - item: function (index) { - return this[index]; - }, - // .removeProperty - removeProperty: function () { - throw new Error('NoModificationAllowedError: DOM Exception 7'); - }, - // .setProperty - setProperty: function () { - throw new Error('NoModificationAllowedError: DOM Exception 7'); - }, - // .getPropertyCSSValue - getPropertyCSSValue: function () { - throw new Error('NotSupportedError: DOM Exception 9'); - } - }; - - // .getComputedStyle - window.getComputedStyle = function getComputedStyle(element) { - return new CSSStyleDeclaration(element); - }; - })(); -} + // Element.prototype.classList by thednp + if( !(classList in ELEMENT[prototype]) ) { + var ClassLIST = function(elem){ + var classArr = elem[className].replace(/^\s+|\s+$/g,'').split(/\s+/) || []; -// Event -if (!window.Event||!Window.prototype.Event) { - (function (){ - window.Event = Window.prototype.Event = Document.prototype.Event = Element.prototype.Event = function Event(type, eventInitDict) { - if (!type) { throw new Error('Not enough arguments'); } - var event, - bubbles = eventInitDict && eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false, - cancelable = eventInitDict && eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false; - if ( 'createEvent' in document ) { - event = document.createEvent('Event'); - event.initEvent(type, bubbles, cancelable); - } else { - event = document.createEventObject(); - event.type = type; - event.bubbles = bubbles; - event.cancelable = cancelable; - } - return event; - }; - })(); -} + // methods + hasClass = this[contains] = function(classNAME){ + return classArr[indexOf](classNAME) > -1; + }, + addClass = this[add] = function(classNAME){ + if (!hasClass(classNAME)) { + classArr.push(classNAME); + elem[className] = classArr.join(' '); + } + }, + removeClass = this[remove] = function(classNAME){ + if (hasClass(classNAME)) { + classArr.splice(classArr[indexOf](classNAME),1); + elem[className] = classArr.join(' '); + } + }, + toggleClass = this.toggle = function(classNAME){ + if ( hasClass(classNAME) ) { removeClass(classNAME); } + else { addClass(classNAME); } + }; + } + Object.defineProperty(ELEMENT[prototype], classList, { get: function () { return new ClassLIST(this); } }); + } -// CustomEvent -if (!('CustomEvent' in window) || !('CustomEvent' in Window.prototype)) { - (function(){ - window.CustomEvent = Window.prototype.CustomEvent = Document.prototype.CustomEvent = Element.prototype.CustomEvent = function CustomEvent(type, eventInitDict) { - if (!type) { - throw Error('TypeError: Failed to construct "CustomEvent": An event name must be provided.'); - } - var event = new Event(type, eventInitDict); - event.detail = eventInitDict && eventInitDict.detail || null; - return event; - }; - - })() -} + // Event + if (!win[EVENT]||!WINDOW[prototype][EVENT]) { + win[EVENT] = WINDOW[prototype][EVENT] = DOCUMENT[prototype][EVENT] = ELEMENT[prototype][EVENT] = function(type, eventInitDict) { + if (!type) { throw new Error('Not enough arguments'); } + var event, + bubblesValue = eventInitDict && eventInitDict[bubbles] !== undefined ? eventInitDict[bubbles] : false, + cancelableValue = eventInitDict && eventInitDict[cancelable] !== undefined ? eventInitDict[cancelable] : false; + if ( 'createEvent' in doc ) { + event = doc.createEvent(EVENT); + event.initEvent(type, bubblesValue, cancelableValue); + } else { + event = doc.createEventObject(); + event[etype] = type; + event[bubbles] = bubblesValue; + event[cancelable] = cancelableValue; + } + return event; + }; + } -// addEventListener -if (!window.addEventListener||!Window.prototype.addEventListener) { - (function (){ - window.addEventListener = Window.prototype.addEventListener = Document.prototype.addEventListener = Element.prototype.addEventListener = function addEventListener() { - var element = this, - type = arguments[0], - listener = arguments[1]; - - if (!element._events) { element._events = {}; } - - if (!element._events[type]) { - element._events[type] = function (event) { - var list = element._events[event.type].list, - events = list.slice(), - index = -1, - length = events.length, - eventElement; - - event.preventDefault = function preventDefault() { - if (event.cancelable !== false) { - event.returnValue = false; - } - }; - - event.stopPropagation = function stopPropagation() { - event.cancelBubble = true; - }; - - event.stopImmediatePropagation = function stopImmediatePropagation() { - event.cancelBubble = true; - event.cancelImmediate = true; - }; - - event.currentTarget = element; - event.relatedTarget = event.fromElement || null; - event.target = event.target || event.srcElement || element; - event.timeStamp = new Date().getTime(); - - if (event.clientX) { - event.pageX = event.clientX + document.documentElement.scrollLeft; - event.pageY = event.clientY + document.documentElement.scrollTop; - } - - while (++index < length && !event.cancelImmediate) { - if (index in events) { - eventElement = events[index]; - - if (list.indexOf(eventElement) !== -1 && typeof eventElement === 'function') { - eventElement.call(element, event); - } - } - } - }; - - element._events[type].list = []; - - if (element.attachEvent) { - element.attachEvent('on' + type, element._events[type]); - } - } - - element._events[type].list.push(listener); - }; - - window.removeEventListener = Window.prototype.removeEventListener = Document.prototype.removeEventListener = Element.prototype.removeEventListener = function removeEventListener() { - var element = this, - type = arguments[0], - listener = arguments[1], - index; - - if (element._events && element._events[type] && element._events[type].list) { - index = element._events[type].list.indexOf(listener); - - if (index !== -1) { - element._events[type].list.splice(index, 1); - - if (!element._events[type].list.length) { - if (element.detachEvent) { - element.detachEvent('on' + type, element._events[type]); - } - delete element._events[type]; - } - } - } - }; - })(); -} + // CustomEvent + if (!(CustomEvent in win) || !(CustomEvent in WINDOW[prototype])) { + win[CustomEvent] = WINDOW[prototype][CustomEvent] = DOCUMENT[prototype][CustomEvent] = Element[prototype][CustomEvent] = function(type, eventInitDict) { + if (!type) { + throw Error('CustomEvent TypeError: An event name must be provided.'); + } + var event = new Event(type, eventInitDict); + event[detail] = eventInitDict && eventInitDict[detail] || null; + return event; + }; + } -// Event dispatcher / trigger -if (!window.dispatchEvent||!Window.prototype.dispatchEvent||!Document.prototype.dispatchEvent||!Element.prototype.dispatchEvent) { - (function(){ - window.dispatchEvent = Window.prototype.dispatchEvent = Document.prototype.dispatchEvent = Element.prototype.dispatchEvent = function dispatchEvent(event) { - if (!arguments.length) { - throw new Error('Not enough arguments'); - } - - if (!event || typeof event.type !== 'string') { - throw new Error('DOM Events Exception 0'); - } - - var element = this, type = event.type; - - try { - if (!event.bubbles) { - event.cancelBubble = true; - - var cancelBubbleEvent = function (event) { - event.cancelBubble = true; - - (element || window).detachEvent('on' + type, cancelBubbleEvent); - }; - - this.attachEvent('on' + type, cancelBubbleEvent); - } - - this.fireEvent('on' + type, event); - } catch (error) { - event.target = element; - - do { - event.currentTarget = element; - - if ('_events' in element && typeof element._events[type] === 'function') { - element._events[type].call(element, event); - } - - if (typeof element['on' + type] === 'function') { - element['on' + type].call(element, event); - } - - element = element.nodeType === 9 ? element.parentWindow : element.parentNode; - } while (element && !event.cancelBubble); - } - - return true; - }; - })(); -} \ No newline at end of file + // addEventListener | removeEventListener + if (!win[addEventListener]||!WINDOW[prototype][addEventListener]) { + win[addEventListener] = WINDOW[prototype][addEventListener] = DOCUMENT[prototype][addEventListener] = ELEMENT[prototype][addEventListener] = function() { + var element = this, + type = arguments[0], + listener = arguments[1]; + + if (!element[IE8EVENTS]) { element[IE8EVENTS] = {}; } + + if (!element[IE8EVENTS][type]) { + element[IE8EVENTS][type] = function (event) { + var list = element[IE8EVENTS][event[etype]].list, + events = list.slice(), + index = -1, + lengthValue = events[length], + eventElement; + + event.preventDefault = function() { + if (event[cancelable] !== false) { + event.returnValue = false; + } + }; + + event.stopPropagation = function() { + event[cancelBubble] = true; + }; + + event.stopImmediatePropagation = function() { + event[cancelBubble] = true; + event[cancelImmediate] = true; + }; + + event[currentTarget] = element; + event[relatedTarget] = event[relatedTarget] || event.fromElement || null; + event[target] = event[target] || event.srcElement || element; + event.timeStamp = new Date().getTime(); + + if (event.clientX) { + event.pageX = event.clientX + doc[documentElement].scrollLeft; + event.pageY = event.clientY + doc[documentElement].scrollTop; + } + + while (++index < lengthValue && !event[cancelImmediate]) { + if (index in events) { + eventElement = events[index]; + + if (list[indexOf](eventElement) !== -1 && typeof eventElement === 'function') { + eventElement.call(element, event); + } + } + } + }; + + element[IE8EVENTS][type].list = []; + + if (element.attachEvent) { + element.attachEvent('on' + type, element[IE8EVENTS][type]); + } + } + + element[IE8EVENTS][type].list.push(listener); + }; + + win[removeEventListener] = WINDOW[prototype][removeEventListener] = DOCUMENT[prototype][removeEventListener] = ELEMENT[prototype][removeEventListener] = function() { + var element = this, + type = arguments[0], + listener = arguments[1], + index; + + if (element[IE8EVENTS] && element[IE8EVENTS][type] && element[IE8EVENTS][type].list) { + index = element[IE8EVENTS][type].list[indexOf](listener); + + if (index !== -1) { + element[IE8EVENTS][type].list.splice(index, 1); + + if (!element[IE8EVENTS][type].list[length]) { + if (element.detachEvent) { + element.detachEvent('on' + type, element[IE8EVENTS][type]); + } + delete element[IE8EVENTS][type]; + } + } + } + }; + } + + // Event dispatcher + if (!win[dispatchEvent]||!WINDOW[prototype][dispatchEvent]||!DOCUMENT[prototype][dispatchEvent]||!ELEMENT[prototype][dispatchEvent]) { + win[dispatchEvent] = WINDOW[prototype][dispatchEvent] = DOCUMENT[prototype][dispatchEvent] = ELEMENT[prototype][dispatchEvent] = function (event) { + if (!arguments[length]) { + throw new Error('Not enough arguments'); + } + + if (!event || typeof event[etype] !== 'string') { + throw new Error('DOM Events Exception 0'); + } + + var element = this, type = event[etype]; + + try { + if (!event[bubbles]) { + event[cancelBubble] = true; + + var cancelBubbleEvent = function (event) { + event[cancelBubble] = true; + + (element || win).detachEvent('on' + type, cancelBubbleEvent); + }; + + this.attachEvent('on' + type, cancelBubbleEvent); + } + + this.fireEvent('on' + type, event); + } catch (error) { + event[target] = element; + + do { + event[currentTarget] = element; + + if (IE8EVENTS in element && typeof element[IE8EVENTS][type] === 'function') { + element[IE8EVENTS][type].call(element, event); + } + + if (typeof element['on' + type] === 'function') { + element['on' + type].call(element, event); + } + + element = element.nodeType === 9 ? element.parentWindow : element.parentNode; + } while (element && !event[cancelBubble]); + } + + return true; + }; + } +}()); \ No newline at end of file diff --git a/demo/assets/js/scripts.js b/demo/assets/js/scripts.js index 292f0b3..7324e88 100644 --- a/demo/assets/js/scripts.js +++ b/demo/assets/js/scripts.js @@ -3,50 +3,37 @@ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } -// utility functions -function addClass(el,c) { // where modern browsers fail, use classList - if (el.classList) { el.classList.add(c); } else { el.className += ' '+c; el.offsetWidth; } -} -function removeClass(el,c) { - if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^\s+|\s+$/g,''); el.offsetWidth; } -} - //scroll top? var toTop = document.getElementById('toTop'), toTopTween = KUTE.to( 'window', { scroll: 0 }, {easing: 'easingQuarticOut', duration : 1500 } ); -toTop.addEventListener('click',topHandler,false); - function topHandler(e){ e.preventDefault(); toTopTween.start(); } +toTop.addEventListener('click',topHandler,false); + // toggles utility var toggles = document.querySelectorAll('[data-function="toggle"]'); -for (var i = 0, l = toggles.length; i< l; i ++ ){ - toggles[i].addEventListener('click', toggleClass, false); -} - -function toggleClass(e){ - e.preventDefault(); - var pr = this.parentNode; - if (!/open/.test(pr.className)){ - addClass(pr,'open'); - } else { - removeClass(pr,'open'); - } -} function closeToggles(el){ - var pr = el.parentNode; - if (/open/.test(pr.className)){ - removeClass(pr,'open'); - } + el.classList.remove('open'); +} + +function classToggles(el){ + el.classList.toggle('open'); } document.addEventListener('click', function(e){ - for (var i = 0, l = toggles.length; i< l; i ++ ){ - if (toggles[i]!==e.target) closeToggles(toggles[i]); + var target = e.target.parentNode.tagName === 'LI' ? e.target : e.target.parentNode, + parent = target.parentNode; + + for (var i = 0, l = toggles.length; i - + + + @@ -12,148 +14,155 @@ - + + KUTE.js Attributes Plugin | Javascript Animation Engine - + - + - + - - - + + + - - - - + + + + + -
- -
- - +
-
-

Attributes Plugin

-

The KUTE.js Attributes Plugin extends the core engine and enables animation for any numeric presentation attribute, with or without a measurement unit or what we know as suffix. The plugin can be a great asset for creating complex animations in combination with the SVG Plugin as we'll see in the following examples. As a quick refference, the basic synthax goes like this:

+
-
// basic synthax for unitless attributes
+        
+
+        
+

Attributes Plugin

+

The KUTE.js Attributes Plugin extends the core engine and enables animation for any numeric presentation attribute, with or without a measurement unit or what we know as suffix. The plugin can be a great asset for creating complex animations + in combination with the SVG Plugin as we'll see in the following examples. As a quick refference, the basic synthax goes like this:

+ +
// basic synthax for unitless attributes
 var myAttrTween = KUTE.to('selector', {attr: {attributeName: 75}});
 
 // OR for attributes that are ALWAYS suffixed / have a measurement unit
 var mySufAttrTween = KUTE.to('selector', {attr:{attributeName: '15%'}});
 
-

The Attributes Plugin does support color attributes such as fill or stroke starting with KUTE.js v1.5.8, but doesn't support attributes with multiple values like stroke-dasharray, viewBox or transform for simplicity reasons. To animate the stroke/fill or transform attribute, the SVG Plugin has some handy solutions for you. Despite the limitations of this plugin, you have access to just about any SVGElement/Element presentation attribute available.

+

The Attributes Plugin does support color attributes such as fill or stroke starting with KUTE.js v1.5.8, but doesn't support attributes with multiple values like stroke-dasharray, viewBox or transform for simplicity reasons. To animate the stroke/fill or transform attribute, the SVG Plugin has some handy solutions for you. Despite the limitations of this plugin, you have access to just + about any SVGElement/Element presentation attribute available.

-

Attributes Namespace

-

Starting with KUTE.js version 1.5.5, the Attributes Plugin can handle all possible single value attributes with both dashed string and non-dashed string notation. Let's have a look at an example so you can get the idea:

-
// dashed attribute notation
+            

Attributes Namespace

+

Starting with KUTE.js version 1.5.5, the Attributes Plugin can handle all possible single value attributes with both dashed string and non-dashed string notation. Let's have a look at an example so you can get the idea:

+
// dashed attribute notation
 var myDashedAttrStringTween = KUTE.to('selector', {attr: {'stroke-width': 75}});
 
 // non-dashed attribute notation
 var myNonDashedAttrStringTween = KUTE.to('selector', {attr:{strokeWidth: '15px'}});
 
-

The strokeWidth example is very interesting because this attribute along with many others can work with px, % or with no unit/suffix.

- -

Color Attributes

-

Starting with KUTE.js version 1.5.7, the Attributes Plugin can also animate color attributes: fill, stroke and stopColor. If the elements are affected by their CSS counterparts, the effect is not visible, so always make sure you know what you're doing.

-
// some fill rgb, rgba, hex
+            

The strokeWidth example is very interesting because this attribute along with many others can work with px, % or with no unit/suffix.

+ +

Color Attributes

+

Starting with KUTE.js version 1.5.7, the Attributes Plugin can also animate color attributes: fill, stroke and stopColor. If the elements are affected by their CSS counterparts, the effect is not visible, + so always make sure you know what you're doing.

+
// some fill rgb, rgba, hex
 var fillTween = KUTE.to('#element-to-fill', {attr: { fill: 'red' }});
-    
+
 // some stopColor or 'stop-color'
 var stopColorTween = KUTE.to('#element-to-do-stop-color', {attr: {stopColor: 'rgb(0,66,99)'}});
 
- -
- + +
+ + c0,17.905-14.517,32.422-32.422,32.422H38.01c-17.906,0-32.422-14.517-32.422-32.422V38.075C5.588,20.169,20.104,5.653,38.01,5.653z"/> - -
- Start -
-
-

If in this example the fill attribute value would reference a gradient, then rgba(0,0,0,0) is used.

-

Unitless Attributes

-

In the first example, let's play with the attributes of a <circle> element: radius and center coordinates.

-
// radius attribute
+                
+ Start +
+
+

If in this example the fill attribute value would reference a gradient, then rgba(0,0,0,0) is used.

+ +

Unitless Attributes

+

In the first example, let's play with the attributes of a <circle> element: radius and center coordinates.

+
// radius attribute
 var radiusTween = KUTE.to('#circle', {attr: {r: 75}});
-    
+
 // coordinates of the circle center
 var coordinatesTween = KUTE.to('#circle', {attr:{cx:0,cy:0}});
-
-

A quick demo with the above:

-

- +
+

A quick demo with the above: +

+

+ - -
- Start -
-
- -

Suffixed Attributes

-

Similar to the example on gradients with SVG Plugin, we can also animate the gradient positions, and the plugin will make sure to always include the suffix for you, as in this example the % unit is found in the current value and used as unit for the DOM update:

-
// gradient positions to middle
+
+                        
+ Start +
+
+ +

Suffixed Attributes

+

Similar to the example on gradients with SVG Plugin, we can also animate the gradient positions, and the plugin will make sure to always include the suffix for you, as in this example the % unit + is found in the current value and used as unit for the DOM update:

+
// gradient positions to middle
 var closingGradient = KUTE.to('#gradient', {attr: {x1:'49%', x2:'49%', y1:'49%', y2:'49%'}});
-    
+
 // gradient positions rotated
 var rotatingGradient = KUTE.to('#gradient', {attr: {x1:'49%', x2:'51%', y1:'51%', y2:'51%'}});
 
- -
- + +
+ @@ -161,47 +170,53 @@ var rotatingGradient = KUTE.to('#gradient', {attr: {x1:'49%', x2:'51%', y1:'51%' + c0,17.905-14.517,32.422-32.422,32.422H38.01c-17.906,0-32.422-14.517-32.422-32.422V38.075C5.588,20.169,20.104,5.653,38.01,5.653z"/> - -
- Start -
-
-

This plugin is quite handy and a great addition to the SVG Plugin.

-
+
+ Start +
+
+

This plugin is quite handy and a great addition to the SVG Plugin.

- +
- - + -
- + + + + + - - + - - + + - - - - - + + + + + + + + + - \ No newline at end of file + + diff --git a/demo/css.html b/demo/css.html index e89d255..85247cf 100644 --- a/demo/css.html +++ b/demo/css.html @@ -3,7 +3,9 @@ - + + + @@ -12,220 +14,232 @@ - + KUTE.js CSS Plugin | Javascript Animation Engine - + - + - + - - - + + + - - - - + + + + + -
- -
- - +
-
-

CSS Plugin

-

The CSS Plugin extends the KUTE.js core engine and enables animation for additional CSS properties as mentioned in the examples page. The focus is on box model properties like padding, margin or borderWidth, as well as other types of properties like borderRadius, borderColor, backgroundPosition, borderColor or clip.

- - -

Border Radius

-

In the example below we are doing some animation on the border-radius property. The first box animates all corners, while the other boxes animate each corner at a time. A quick reminder, for radius properties KUTE.js supports px, % and text properties' units such as em or rem.

-
KUTE.to('selector1',{borderRadius:'100%'}).start();
+    
+ + + +
+

CSS Plugin

+

The CSS Plugin extends the KUTE.js core engine and enables animation for additional CSS properties as mentioned in the examples page. The focus is on box model properties like padding, margin or borderWidth, as well as other types of properties like borderRadius, borderColor, backgroundPosition, borderColor or clip.

+ + +

Border Radius

+

In the example below we are doing some animation on the border-radius property. The first box animates all corners, while the other boxes animate each corner at a time. A quick reminder, for radius properties KUTE.js supports + px, % and text properties' units such as em or rem.

+
KUTE.to('selector1',{borderRadius:'100%'}).start();
 KUTE.to('selector2',{borderTopLeftRadius:'100%'}).start();
 KUTE.to('selector3',{borderTopRightRadius:'100%'}).start();
 KUTE.to('selector4',{borderBottomLeftRadius:'100%'}).start();
 KUTE.to('selector5',{borderBottomRightRadius:'100%'}).start();
-
+
-

And here is how it looks like:

+

And here is how it looks like:

-
-
ALL
-
TL
-
TR
-
BL
-
BR
- -
- Start -
-
- -

A quick important reminder here is that KUTE.js does not support shorthands for radius properties. Also early implementations by Mozilla's Firefox browser like -moz-border-radius-topleft are not supported because they were depracated with later versions. Download this example here.

- -

Box Model Properties

-

The CSS Plugin allows KUTE.js to support almost all the box model properties, but for our example here we will focus mostly on margin and padding, as other properties such as outlineWidth, minWidth or maxHeight require a more complex context and we won't insist on them.

-
var tween1 = KUTE.to('selector1',{marginTop:200});
+            
+
ALL
+
TL
+
TR
+
BL
+
BR
+ +
+ Start +
+
+ +

A quick important reminder here is that KUTE.js does not support shorthands for radius properties. Also early implementations by Mozilla's Firefox browser like -moz-border-radius-topleft are not supported because they were depracated + with later versions. Download this example here.

+ +

Box Model Properties

+

The CSS Plugin allows KUTE.js to support almost all the box model properties, but for our example here we will focus mostly on margin and padding, as other properties such as outlineWidth, minWidth or maxHeight require a more complex context and we won't insist on them.

+
var tween1 = KUTE.to('selector1',{marginTop:200});
 var tween2 = KUTE.to('selector1',{marginBottom:50});
 var tween3 = KUTE.to('selector1',{padding:30});
 var tween4 = KUTE.to('selector1',{margin:'5%'});
 
-

We're gonna chain these tweens and start the animation. You can download this example here.

-
-
BOX
 MODEL 
- -
- Start -
-
- - -

TIP: the width and height properties used together can be great for scale animation fallback on images for legacy browsers.

- -

Text Properties

-

OK here we're gonna do a cool example for text properties. Basically the below code would work:

-
var tween1 = KUTE.to('selector1',{fontSize:'200%'});
+            

We're gonna chain these tweens and start the animation. You can download this example here.

+
+
BOX
 MODEL 
+ +
+ Start +
+
+ + +

TIP: the width and height properties used together can be great for scale animation fallback on images for legacy browsers.

+ +

Text Properties

+

OK here we're gonna do a cool example for text properties. Basically the below code would work:

+
var tween1 = KUTE.to('selector1',{fontSize:'200%'});
 var tween2 = KUTE.to('selector1',{lineHeight:24});
 var tween3 = KUTE.to('selector1',{letterSpacing:50});
 var tween3 = KUTE.to('selector1',{wordSpacing:50});
 
-

But our example will feature some more than just that. We're gonna animate each character of a given string, with a small delay. The heading will animate fontSize and letterSpacing properties for each character while the button will animate fontSize and lineHeight properties. Watch this:

- -
-

Howdy!

- Button - - -
-

TIP: this should also work in Internet Explorer 8 as a fallback for scale animation for text. The above example uses some CSS hacks to enable opacity animation on IE8, so make sure to check assets/css/css.css file for more. This example is not perfect, as legacy browsers don't support the excellent transform functions with subpixel animations, but if it's a must, this would do. Download this example here.

+

But our example will feature some more than just that. We're gonna animate each character of a given string, with a small delay. The heading will animate fontSize and letterSpacing properties for each character while + the button will animate fontSize and lineHeight properties. Watch this:

-

Color Properties

-

The next example is about animating all border color properties, since the core engine already supports text color and backgroundColor properties. So check these lines for reference.

-
KUTE.to('selector1',{borderColor:'rgb(25,25,25)'}).start();
+            
+

Howdy!

+ Button + + +
+

TIP: this should also work in Internet Explorer 8 as a fallback for scale animation for text. The above example uses some CSS hacks to enable opacity animation on IE8, so make sure to check assets/css/css.css file for more. This + example is not perfect, as legacy browsers don't support the excellent transform functions with subpixel animations, but if it's a must, this would do. Download this example here.

+ +

Color Properties

+

The next example is about animating all border color properties, since the core engine already supports text color and backgroundColor properties. So check these lines for reference.

+
KUTE.to('selector1',{borderColor:'rgb(25,25,25)'}).start();
 KUTE.to('selector1',{borderTopColor:'#069'}).start();
 KUTE.to('selector1',{borderRightColor:'rgba(25,25,25,0.25)'}).start();
 KUTE.to('selector1',{borderBottomColor:'red'}).start(); // IE9+ browsers
 KUTE.to('selector1',{borderLeftColor:'#069'}).start();
 KUTE.to('selector1',{outlineColor:'#069'}).start();
 
-

Let's get some animation going. Download the example here.

- -
-
Colors
- -
- Start -
-
+

Let's get some animation going. Download the example here.

-

A quick reminder: you can also use RGB or RGBA, but the last one is not supported on IE8 and it will fallback to RGB.

+
+
Colors
-

Clip Property

-

This property allows you to animate the rectangular shape of an element that is set to position:absolute. In CSS this property works like this clip: rect(top,right,bottom,left) forming a rectangular shape that masks an element making parts of it invisible.

-
KUTE.to('selector',{clip:[0,150,100,0]}).start();
-

A quick example here could look like this:

- -
-
- -
- Start -
-
-

Note that this would produce no effect for elements that have overflow:visible style rule. Download this example here.

+
+ Start +
+
-

Background Position

-

Another property we can animate with KUTE.js is backgroundPosition. Quick example:

-
KUTE.to('selector1',{backgroundPosition:[0,50]}).start();
-

A working example would look like this:

- -
-
- -
- Start -
-
-

Download this example here.

+

A quick reminder: you can also use RGB or RGBA, but the last one is not supported on IE8 and it will fallback to RGB.

-
+

Clip Property

+

This property allows you to animate the rectangular shape of an element that is set to position:absolute. In CSS this property works like this clip: rect(top,right,bottom,left) forming a rectangular shape that masks + an element making parts of it invisible.

+
KUTE.to('selector',{clip:[0,150,100,0]}).start();
+

A quick example here could look like this:

- +
+
- - +
+ Start +
+
+

Note that this would produce no effect for elements that have overflow:visible style rule. Download this example here.

-
- +

Background Position

+

Another property we can animate with KUTE.js is backgroundPosition. Quick example:

+
KUTE.to('selector1',{backgroundPosition:[0,50]}).start();
+

A working example would look like this:

+ +
+
+ +
+ Start +
+
+

Download this example here.

+ + + + + + + + + + - - + - - + + - - - - - + + + + + + + + + - \ No newline at end of file + + diff --git a/demo/easing.html b/demo/easing.html index f5e16b5..6125492 100644 --- a/demo/easing.html +++ b/demo/easing.html @@ -3,7 +3,9 @@ - + + + @@ -12,323 +14,352 @@ - + + KUTE.js Easing Functions | Javascript Animation Engine - + - + - + - - - + + + - - - - - + + + + + + -
- - + -
+
-

Easing Functions

-

The easing functions generally make animations closer to reality and completely eliminate the boring factor for a given context. The most simple example to understand what they do, think of gravity. Dropping an object from a given height, will start moving to the ground with accelerated speed. If the object has some sort of bounciness like a ball, it will jump back up and up again, till the gravity will eventually stick the object to the ground.

-

What scientists observed and put in theory houndreads of years ago, later the pioneers of scripting started to implement the laws of physics into digital animation and came up with this notion of easing to describe the progression of movement. If you care to dig into the concept, here's an excellent resource some developers recommend. I would also recommend this one too.

- -

Core Functions

-

Modern browsers that support transition can also make use of some generic easing functions via the CSS3 transition-timing-function:ease-out property, but in Javascript animation, we need some special functions. The popular Robert Penner's easing functions set is the default set included with KUTE.js because it's the fastest set I know in terms of performance. Some functions may lack a bit of accuracy but they cover the most animation needs. Generally the easing functions' names are built with keywords that describe the type of easing, like circular or exponential, and also the type of progression in and/or out.

- -

To use them, simply set a tween option like so easing: KUTE.Easing.easingSinusoidalInOut or simply easing: 'easingSinusoidalInOut'.

-

linear is the default easing function and just as it sounds, it means that the animation has no acceleration or deceleration over time. While this one is basically boring, it's the fastest in all, and it's very useful when animating opacity or colors because we cannot really distinguish changes in speed for such cases, but mostly for movement.

- -

curve based functions are the next set of easings we are going to talk about. They are basically the same, the only difference is the number of multipliers applied (better think of it like the more weight an object has, the more acceleration):

-
    -
  • Sinusoidal - multiplier of 1 (super light object, like a feather)
  • -
  • Quadratic - multiplier of 2
  • -
  • Cubic - multiplier of 3
  • -
  • Quartic - multiplier of 4
  • -
  • Quintic - multiplier of 5
  • -
  • Circular - multiplier of 6
  • -
  • Exponential - multiplier of 10 (super heavy object, like a truck)
  • -
- -

The In / Out explained:

-
    -
  • In - means that the animation starts with very very low speed and gains acceleration over time, but when it reaches the maximum speed, animation stops. These functions are: easingSinusoidalIn, easingQuadraticIn,easingCubicIn, easingQuarticIn, easingQuinticIn, easingCircularIn and easingExponentialIn.
  • -
  • Out - means that the animation starts with maximum speed and constantly decelerates over time until the animation stops. These functions are: easingSinusoidalOut, easingQuadraticOut, easingCubicOut, easingQuarticOut, easingQuinticOut, easingCircularOut and easingExponentialOut.
  • -
  • InOut - means that the animation accelerates halfway until it reaches the maximum speed, then begins to decelerate until it stops. These functions are: easingSinusoidalInOut, easingQuadraticInOut, easingCubicInOut, easingQuarticInOut, easingQuinticInOut, easingCircularInOut and easingExponentialInOut.
  • -
- -

back easing functions describe more complex animations (I would call them reverse gravity easings). They also come with in and/or out types of progression.

-
    -
  • easingBackIn would be best described when you throw an object into the air with a small amount of physical power, it will move up decelerating until it stops, then will move to the ground with acceleration.
  • -
  • easingBackOut would be best described as the previous function, but viewed in reverse mode.
  • -
  • easingBackInOut is a combination of the other two.
  • -
- -

elasticity easing functions describe the kind of animation where the object is elastic. With in and/or out as well.

-
    -
  • easingElasticOut would be best described by the movement of a guitar string after being pinched, moving up and down, with decreasing frequency, until it stops.
  • -
  • easingElasticIn would be best described as the above function but viewed in reverse mode.
  • -
  • easingElasticInOut is simply a combination of the other two.
  • -
- -

gravity based easing functions describe the kind of animation where the object has a certain degree of bounciness, like a ball. With in and/or out as well.

-
    -
  • easingBounceOut looks just like a ball falling on the ground and start boucing up and down with decreasing frequency untill it stops.
  • -
  • easingBounceIn looks like the previous viewed in reverse mode
  • -
  • easingBounceInOut is a combination of the other two.
  • -
+

Easing Functions

+

The easing functions generally make animations closer to reality and completely eliminate the boring factor for a given context. The most simple example to understand what they do, think of gravity. Dropping an object from a given height, + will start moving to the ground with accelerated speed. If the object has some sort of bounciness like a ball, it will jump back up and up again, till the gravity will eventually stick the object to the ground.

+

What scientists observed and put in theory houndreads of years ago, later the pioneers of scripting started to implement the laws of physics into digital animation and came up with this notion of easing to describe the progression of movement. + If you care to dig into the concept, here's an excellent resource some developers recommend. I would also recommend + this one too.

-

Core easing functions examples:

-
-
Linear
-
- -
-
- Select -
    -
  • easingSinusoidalIn
  • -
  • easingSinusoidalOut
  • -
  • easingSinusoidalInOut
  • -
  • easingQuadraticIn
  • -
  • easingQuadraticOut
  • -
  • easingQuadraticInOut
  • -
  • easingCubicIn
  • -
  • easingCubicOut
  • -
  • easingCubicInOut
  • -
  • easingQuarticIn
  • -
  • easingQuarticOut
  • -
  • easingQuarticInOut
  • -
  • easingQuinticIn
  • -
  • easingQuinticOut
  • -
  • easingQuinticInOut
  • -
  • easingCircularIn
  • -
  • easingCircularOut
  • -
  • easingCircularInOut
  • -
  • easingExponentialIn
  • -
  • easingExponentialOut
  • -
  • easingExponentialInOut
  • -
  • easingBackIn
  • -
  • easingBackOut
  • -
  • easingBackInOut
  • -
  • easingElasticIn
  • -
  • easingElasticOut
  • -
  • easingElasticInOut
  • -
-
- Start -
-
- -

Cubic Bezier Functions

-

While modern browsers support CSS3 transition with transition-timing-function: cubic-bezier(0.1,0.5,0.8,0.5), in Javascript animation we need some specific functions to cover that kind of functionality. As mentioned in the features page, we are using a modified version of the cubic-bezier by Gaëtan Renaudeau. I believe this must be most accurate easing functions set.

-

You can use them either with easing: Bezier(mX1, mY1, mX2, mY2) or easing: 'bezier(mX1, mY1, mX2, mY2)', where mX1, mY1, mX2, mY2 are Float values from 0 to 1. You can find the right values you need right here.

-

NOTE: Starting with KUTE.js v 1.6.0 the Cubic Bezier Functions are removed from the distribution folder and from CDN repositories, but you can find them in the Experiments repository on Github.

-

There is also a pack of presets, and the keywords look very similar if you have used jQuery.Easing plugin before:

-
    -
  • Equivalents of the browser's generic timing functions: easeIn, easeOut and easeInOut
  • -
  • Sinusoidal timing functions: easeInSine, easeOutSine and easeInOutSine
  • -
  • Quadratic timing functions: easeInQuad, easeOutQuad and easeInOutQuad
  • -
  • Cubic timing functions: easeInCubic, easeOutCubic and easeInOutCubic
  • -
  • Quartic timing functions: easeInQuart, easeInQuart and easeInOutQuart
  • -
  • Quintic timing functions: easeInQuint, easeOutQuint and easeInOutQuint
  • -
  • Exponential timing functions: easeInExpo, easeOutExpo and easeInOutExpo
  • -
  • Back timing functions: easeInBack, easeOutBack and easeInOutBack
  • -
  • Special slow motion timing functions look like this: slowMo, slowMo1 and slowMo2
  • -
-

Cubic-bezier easing functions examples:

-
-
Linear
-
- -
-
- Select -
    -
  • bezier(0.15, 0.7, 0.2, 0.9)
  • -
  • bezier(0.25, 0.5, 0.6, 0.7)
  • -
  • bezier(0.35, 0.2, 0.9, 0.2)
  • -
  • easeIn
  • -
  • easeOut
  • -
  • easeInOut
  • -
  • easeInSine
  • -
  • easeOutSine
  • -
  • easeInOutSine
  • -
  • easeInQuad
  • -
  • easeOutQuad
  • -
  • easeInOutQuad
  • -
  • easeInCubic
  • -
  • easeOutCubic
  • -
  • easeInOutCubic
  • -
  • easeInQuart
  • -
  • easeOutQuart
  • -
  • easeInOutQuart
  • -
  • easeInQuint
  • -
  • easeOutQuint
  • -
  • easeInOutQuint
  • -
  • easeInExpo
  • -
  • easeOutExpo
  • -
  • easeInOutExpo
  • -
  • easeInCirc
  • -
  • easeOutCirc
  • -
  • easeInOutCirc
  • -
  • easeInBack
  • -
  • easeOutBack
  • -
  • easeInOutBack
  • -
  • slowMo
  • -
  • slowMo1
  • -
  • slowMo2
  • -
-
- Start -
-
+

Core Functions

+

Modern browsers that support transition can also make use of some generic easing functions via the CSS3 transition-timing-function:ease-out property, but in Javascript animation, we need some special functions. The + popular Robert Penner's easing functions set is the default set included with KUTE.js because it's the fastest set I know in terms of performance. Some functions may lack a bit of + accuracy but they cover the most animation needs. Generally the easing functions' names are built with keywords that describe the type of easing, like circular or exponential, and also the type of progression in and/or out.

- -

Physics Based Functions

-

KUTE.js also packs the dynamics physics easing functions by Michael Villar and I have to say these functions are amazing in terms of flexibility, control and performance. They allow you to control the friction, bounciness, frequency, elasticity, or multiple bezier points for your animations.

-

NOTE: Starting with KUTE.js v 1.6.0 the Physics Functions are removed from the distribution folder and from CDN repositories, but you can find them in the Experiments repository on Github.

-

You can use them either with regular Javascript invocation as shown below and configure / visualize them on the author's website, while you can also use the pack of presets featuring mostly bezier based functions. Ok now, let's get to it:

- -
    -
  • spring function is basically an elastic type of easing that allows you to set frequency:1-1000, friction:1-1000, anticipationSize:0-1000 (a kind of delay in miliseconds) and anticipationStrength:0-1000 (a kind of a new curve to add to the function while waiting the anticipationSize). Usage: easing: spring({friction:100,frequency:600}).
  • -
  • bounce function is also an elastic easing function, but it works different than Robert Penner's version that's basically a gravity based function. This one here will always come back to the starting values. This function allows you to set frequency:0-1000 and friction:0-1000. Usage: easing: bounce({friction:100,frequency:600}).
  • -
  • gravity function does what a ball dropped on the ground does, bounces until it stops. It allows you to set: elasticity:1-1000 and bounciness:0-1000. Usage: easing: gravity({elasticity:100,bounciness:600}).
  • -
  • forceWithGravity function acts just like gravity except that the ball instead of being dropped it's thrown into the air. This allows you to set same options: elasticity:1-1000 and bounciness:0-1000. Usage: easing: forceWithGravity({elasticity:100,bounciness:600}).
  • -
  • bezier easing function is a bit more complicated as it allows you to set multiple points of bezier curves. Usage: easing: BezierMultiPoint({points:POINTS_ARRAY_COMES HERE}), again use the author's website, edit the bezier curve as you wish and copy paste the points array into this function. Here's how a basic easeIn looks like: -
    // sample bezier based easing
    +            

    To use them, simply set a tween option like so easing: KUTE.Easing.easingSinusoidalInOut or simply easing: 'easingSinusoidalInOut'.

    +

    linear is the default easing function and just as it sounds, it means that the animation has no acceleration or deceleration over time. While this one is basically boring, it's the fastest in all, and it's very useful when animating + opacity or colors because we cannot really distinguish changes in speed for such cases, but mostly for movement.

    + +

    curve based functions are the next set of easings we are going to talk about. They are basically the same, the only difference is the number of multipliers applied (better think of it like the more weight an object has, the more + acceleration):

    +
      +
    • Sinusoidal - multiplier of 1 (super light object, like a feather)
    • +
    • Quadratic - multiplier of 2
    • +
    • Cubic - multiplier of 3
    • +
    • Quartic - multiplier of 4
    • +
    • Quintic - multiplier of 5
    • +
    • Circular - multiplier of 6
    • +
    • Exponential - multiplier of 10 (super heavy object, like a truck)
    • +
    + +

    The In / Out explained:

    +
      +
    • In - means that the animation starts with very very low speed and gains acceleration over time, but when it reaches the maximum speed, animation stops. These functions are: easingSinusoidalIn, easingQuadraticIn,easingCubicIn, + easingQuarticIn, easingQuinticIn, easingCircularIn and easingExponentialIn.
    • +
    • Out - means that the animation starts with maximum speed and constantly decelerates over time until the animation stops. These functions are: easingSinusoidalOut, easingQuadraticOut, easingCubicOut, + easingQuarticOut, easingQuinticOut, easingCircularOut and easingExponentialOut.
    • +
    • InOut - means that the animation accelerates halfway until it reaches the maximum speed, then begins to decelerate until it stops. These functions are: easingSinusoidalInOut, easingQuadraticInOut, + easingCubicInOut, easingQuarticInOut, easingQuinticInOut, easingCircularInOut and easingExponentialInOut.
    • +
    + +

    back easing functions describe more complex animations (I would call them reverse gravity easings). They also come with in and/or out types of progression.

    +
      +
    • easingBackIn would be best described when you throw an object into the air with a small amount of physical power, it will move up decelerating until it stops, then will move to the ground with acceleration.
    • +
    • easingBackOut would be best described as the previous function, but viewed in reverse mode.
    • +
    • easingBackInOut is a combination of the other two.
    • +
    + +

    elasticity easing functions describe the kind of animation where the object is elastic. With in and/or out as well.

    +
      +
    • easingElasticOut would be best described by the movement of a guitar string after being pinched, moving up and down, with decreasing frequency, until it stops.
    • +
    • easingElasticIn would be best described as the above function but viewed in reverse mode.
    • +
    • easingElasticInOut is simply a combination of the other two.
    • +
    + +

    gravity based easing functions describe the kind of animation where the object has a certain degree of bounciness, like a ball. With in and/or out as well.

    +
      +
    • easingBounceOut looks just like a ball falling on the ground and start boucing up and down with decreasing frequency untill it stops.
    • +
    • easingBounceIn looks like the previous viewed in reverse mode
    • +
    • easingBounceInOut is a combination of the other two.
    • +
    + +

    Core easing functions examples:

    +
    +
    Linear
    +
    + +
    +
    + Select +
      +
    • easingSinusoidalIn
    • +
    • easingSinusoidalOut
    • +
    • easingSinusoidalInOut
    • +
    • easingQuadraticIn
    • +
    • easingQuadraticOut
    • +
    • easingQuadraticInOut
    • +
    • easingCubicIn
    • +
    • easingCubicOut
    • +
    • easingCubicInOut
    • +
    • easingQuarticIn
    • +
    • easingQuarticOut
    • +
    • easingQuarticInOut
    • +
    • easingQuinticIn
    • +
    • easingQuinticOut
    • +
    • easingQuinticInOut
    • +
    • easingCircularIn
    • +
    • easingCircularOut
    • +
    • easingCircularInOut
    • +
    • easingExponentialIn
    • +
    • easingExponentialOut
    • +
    • easingExponentialInOut
    • +
    • easingBackIn
    • +
    • easingBackOut
    • +
    • easingBackInOut
    • +
    • easingElasticIn
    • +
    • easingElasticOut
    • +
    • easingElasticInOut
    • +
    +
    + Start +
    +
    + +

    Cubic Bezier Functions

    +

    While modern browsers support CSS3 transition with transition-timing-function: cubic-bezier(0.1,0.5,0.8,0.5), in Javascript animation we need some specific functions to cover that kind of functionality. As mentioned + in the features page, we are using a modified version of the cubic-bezier by Gaëtan Renaudeau. I believe this must be most accurate easing functions + set.

    +

    You can use them either with easing: Bezier(mX1, mY1, mX2, mY2) or easing: 'bezier(mX1, mY1, mX2, mY2)', where mX1, mY1, mX2, mY2 are Float values from 0 to 1. You can find the right values you need + right here.

    +

    NOTE: Starting with KUTE.js v 1.6.0 the Cubic Bezier Functions are removed from the distribution folder and from CDN repositories, but you can find them in the Experiments repository on Github.

    +

    There is also a pack of presets, and the keywords look very similar if you have used jQuery.Easing plugin before:

    +
      +
    • Equivalents of the browser's generic timing functions: easeIn, easeOut and easeInOut
    • +
    • Sinusoidal timing functions: easeInSine, easeOutSine and easeInOutSine
    • +
    • Quadratic timing functions: easeInQuad, easeOutQuad and easeInOutQuad
    • +
    • Cubic timing functions: easeInCubic, easeOutCubic and easeInOutCubic
    • +
    • Quartic timing functions: easeInQuart, easeInQuart and easeInOutQuart
    • +
    • Quintic timing functions: easeInQuint, easeOutQuint and easeInOutQuint
    • +
    • Exponential timing functions: easeInExpo, easeOutExpo and easeInOutExpo
    • +
    • Back timing functions: easeInBack, easeOutBack and easeInOutBack
    • +
    • Special slow motion timing functions look like this: slowMo, slowMo1 and slowMo2
    • +
    +

    Cubic-bezier easing functions examples:

    +
    +
    Linear
    +
    + +
    +
    + Select +
      +
    • bezier(0.15, 0.7, 0.2, 0.9)
    • +
    • bezier(0.25, 0.5, 0.6, 0.7)
    • +
    • bezier(0.35, 0.2, 0.9, 0.2)
    • +
    • easeIn
    • +
    • easeOut
    • +
    • easeInOut
    • +
    • easeInSine
    • +
    • easeOutSine
    • +
    • easeInOutSine
    • +
    • easeInQuad
    • +
    • easeOutQuad
    • +
    • easeInOutQuad
    • +
    • easeInCubic
    • +
    • easeOutCubic
    • +
    • easeInOutCubic
    • +
    • easeInQuart
    • +
    • easeOutQuart
    • +
    • easeInOutQuart
    • +
    • easeInQuint
    • +
    • easeOutQuint
    • +
    • easeInOutQuint
    • +
    • easeInExpo
    • +
    • easeOutExpo
    • +
    • easeInOutExpo
    • +
    • easeInCirc
    • +
    • easeOutCirc
    • +
    • easeInOutCirc
    • +
    • easeInBack
    • +
    • easeOutBack
    • +
    • easeInOutBack
    • +
    • slowMo
    • +
    • slowMo1
    • +
    • slowMo2
    • +
    +
    + Start +
    +
    + + +

    Physics Based Functions

    +

    KUTE.js also packs the dynamics physics easing functions by Michael Villar and I have to say these functions are amazing in terms of flexibility, control and performance. They allow you + to control the friction, bounciness, frequency, elasticity, or multiple bezier points for your animations.

    +

    NOTE: Starting with KUTE.js v 1.6.0 the Physics Functions are removed from the distribution folder and from CDN repositories, but you can find them in the Experiments repository on Github.

    +

    You can use them either with regular Javascript invocation as shown below and configure / visualize them on the author's website, while you can also use the pack of presets featuring mostly + bezier based functions. Ok now, let's get to it:

    + +
      +
    • spring function is basically an elastic type of easing that allows you to set frequency:1-1000, friction:1-1000, anticipationSize:0-1000 (a kind of delay in miliseconds) + and anticipationStrength:0-1000 (a kind of a new curve to add to the function while waiting the anticipationSize). Usage: easing: spring({friction:100,frequency:600}).
    • +
    • bounce function is also an elastic easing function, but it works different than Robert Penner's version that's basically a gravity based function. This one here will always come back to the + starting values. This function allows you to set frequency:0-1000 and friction:0-1000. Usage: easing: bounce({friction:100,frequency:600}).
    • +
    • gravity function does what a ball dropped on the ground does, bounces until it stops. It allows you to set: elasticity:1-1000 and bounciness:0-1000. Usage: easing: gravity({elasticity:100,bounciness:600}).
    • +
    • forceWithGravity function acts just like gravity except that the ball instead of being dropped it's thrown into the air. This allows you to set same options: elasticity:1-1000 and bounciness:0-1000. + Usage: easing: forceWithGravity({elasticity:100,bounciness:600}).
    • +
    • bezier easing function is a bit more complicated as it allows you to set multiple points of bezier curves. Usage: easing: BezierMultiPoint({points:POINTS_ARRAY_COMES HERE}), again use the author's website, + edit the bezier curve as you wish and copy paste the points array into this function. Here's how a basic easeIn looks like: +
      // sample bezier based easing
       easing: BezierMultiPoint({points: [{"x":0,"y":0,"cp":[{"x":0.483,"y":0.445}]},{"x":1,"y":1,"cp":[{"x":0.009,"y":0.997}]}] });
      -
      - In other cases, the bezier can handle multiple points as well, basically unlimited: -
      // multi point bezier easing
      +
      In other cases, the bezier can handle multiple points as well, basically unlimited: +
      // multi point bezier easing
       easing: BezierMultiPoint({points: [{"x":0,"y":0,"cp":[{"x":0.387,"y":0.007}]},{"x":0.509,"y":0.48,"cp":[{"x":0.069,"y":0.874},{"x":0.928,"y":0.139}]},{"x":1,"y":1,"cp":[{"x":0.639,"y":0.988}]}] });
      -
      -
    • -
    -

    The presets can be used both as a string easing:'physicsIn' or easing: Physics.physicsIn(friction:200). The list is:

    -
      -
    • curves: physicsIn, physicsOut, physicsInOut can do all multipliers (from sinusoidal to exponential) via the friction option;
    • -
    • back: physicsBackIn, physicsBackOut, physicsBackInOut also benefit from the friction option.
    • -
    -

    Physics easing functions examples:

    -
    -
    Linear
    -
    - -
    -
    - Select -
      -
    • physicsIn
    • -
    • physicsOut
    • -
    • physicsInOut
    • -
    • physicsBackIn
    • -
    • physicsBackOut
    • -
    • physicsBackInOut
    • -
    • spring
    • -
    • bounce
    • -
    • gravity
    • -
    • forceWithGravity
    • -
    • bezier
    • -
    • multiPointBezier
    • -
    -
    - Start -
    -
    - -
+ + + +

The presets can be used both as a string easing:'physicsIn' or easing: Physics.physicsIn(friction:200). The list is:

+
    +
  • curves: physicsIn, physicsOut, physicsInOut can do all multipliers (from sinusoidal to exponential) via the friction option;
  • +
  • back: physicsBackIn, physicsBackOut, physicsBackInOut also benefit from the friction option.
  • +
+

Physics easing functions examples:

+
+
Linear
+
-
+
+
+ Select +
    +
  • physicsIn
  • +
  • physicsOut
  • +
  • physicsInOut
  • +
  • physicsBackIn
  • +
  • physicsBackOut
  • +
  • physicsBackInOut
  • +
  • spring
  • +
  • bounce
  • +
  • gravity
  • +
  • forceWithGravity
  • +
  • bezier
  • +
  • multiPointBezier
  • +
+
+ Start +
+
- - -
- - - +
- - +
+ + + +
+ + + + + + - - + - - + + - + - - - - - + + + + + + + + + + - \ No newline at end of file + + diff --git a/demo/examples.html b/demo/examples.html index f711864..b3ce590 100644 --- a/demo/examples.html +++ b/demo/examples.html @@ -1,506 +1,534 @@ - - - - - - - - - - - - - - - - - KUTE.js Core Engine Examples | Javascript Animation Engine - - - - - - - - - - - - - - - - - - - - - -
- -
- - - -
-

Core Engine

-

KUTE.js core engine can animate by itself a great deal of CSS properties as well as scroll. You can do it all with native Javascript or with jQuery, but before we head over to the more advanced examples, let's have a quick look at these two basic examples here. Note: the examples are posted on codepen.

- -

Basic Native Javascript Example

-

When developing with native Javascript, a very basic syntax goes like this:

- -
-// this is the tween object, basically KUTE.method(element, from, to, options);
-var tween = KUTE.fromTo('selector', {left: 0}, {left: 100}, {yoyo: true});
-
- -

Now the tween object is created, it's a good time for you to know that via Native Javascript we always animate the first HTML element only, even if you're using a class selector. To create/control a tween for multiple elements such as querySelectorAll() or getElementsByTagName(), you need to do a for () loop, or make use of the two new methods: .allTo() or .allFromTo(). Now let's apply the tween control methods:

- -
tween.start(); // starts the animation
-tween.stop(); // stops current tween and all chained tweens animating
-tween.pause(); // pauses current tween animation
-tween.play(); // or tween.resume(); resumes current tween animation
-tween.chain(tween2); // when tween animation finished, you can trigger the start of another tween
-tween.playing // checks if the tween is currenlty active so we prevent start() when not needed
-tween.paused // checks if the tween is currenlty active so we can prevent pausing or resume if needed
-
- -

The demo for the above example is here.

- -

Basic jQuery Example

-

KUTE.js includes a jQuery Plugin to help you easily implement KUTE.js in your jQuery applications. When using jQuery, the syntax is familiar but works a bit different than plain Javascript due to jQuery's specific code standards. Let's have a look:

-
// this is the tween object, basically $('selector').method(fromValues, toValue, options)
-var tween = $('selector').fromTo({top: 20}, {top: 100}, {delay: 500});
-
-

We mentioned that the jQuery Plugin is different, and here's why: the above function call uses the allFromTo method to create an Array of objects for each HTML element of chosen selector, but if the selector only returns one element the call returns a single tween object built with fromTo method. For the array of objects we can now apply the exact same tween control methods, except these:

-
tween.length // check if the tween is an array of objects
-tween.length && tween.tweens[0].playing && tween.tweens[tween.length-1].playing // now we know that one of the tweens is playing
-tween.length && tween.tweens[0].paused && tween.tweens[tween.length-1].paused // now we know that one of the tweens is paused
-
- -

The demo for the above example is here.

- -

Transform Properties Examples

-

KUTE.js supports almost all about transform as described in the spec: the 2D translate, rotate, skewX, skewY and scale, as well as the 3D translateX, translateY, translateZ, translate3d, rotateX, rotateY, rotateZ properties. Additionally it allows you to set a perspective for the element or it's parent as well as a perpective-origin for the element or it's parent.

- -

Translations

-

In the next example the first box is moving to left 250px with translate property, the second box is moving to the right by 200px using translateX and the third box is moving to the bottom using translate3d. The last box also uses translate3d but requires a perspective value for the animation on the Z axis to be effective.

-
var tween1 = KUTE.fromTo('selector1',{translate:0},{translate:-250}); // or translate:[x,y] for both axis
-var tween2 = KUTE.fromTo('selector2',{translateX:0},{translateX:200});
-var tween3 = KUTE.fromTo('selector3',{translate3d:[0,0,0]},{translate3d:[0,100,0]});
-var tween4 = KUTE.fromTo('selector4',{translate3d:[0,0,0]},{translate3d:[0,0,-100]},{parentPerspective: 100});
-
-

And here is how it looks like:

-
-
2D
-
X
-
Y
-
Z
- -
- Start -
-
- -

As you can see in your browsers console, for all animations translate3d is used, as explained in the features page. Also the first example that's using the 2D translate for both vertical and horizontal axis even if we only set X axis. You can download this example here.

-

Remember: stacking translate and translate3d together may not work and IE9 does not support perspective.

- -

Rotations

-

Next we're gonna animate 4 elements with one axis each element. Unlike translations, KUTE.js does not support rotate3d.

- -
var tween1 = KUTE.fromTo('selector1',{rotate:0},{rotate:-720});
-var tween2 = KUTE.fromTo('selector2',{rotateX:0},{rotateX:200});
-var tween3 = KUTE.fromTo('selector3',{rotateY:0},{rotateY:160},{perspective:100});
-var tween4 = KUTE.fromTo('selector4',{rotateZ:0},{rotateZ:360});
-
- -

And here is how it looks like:

-
-
2D
-
X
-
Y
-
Z
-
- Start -
-
-

The rotateX and rotateY are 3D based rotations, so they require a perspective in order to make the browser render proper 3D layers, but in the example they animate different because only the second, Y axis, uses a perspective setting. The rotation on Z axis does not require a perspective. Unlike translations, you can stack all axis rotation for your animation, but we will see that in a later example. You can download this example here.

- -

Skews

-

KUTE.js supports skewX and skewY so let's animate the two. Since they are 2D transformations, IE9 supports skews.

-
var tween1 = KUTE.fromTo('selector1',{skewX:0},{skewX:20});
-var tween2 = KUTE.fromTo('selector2',{skewY:0},{skewY:45});
-
- -

And here is how it looks like:

-
-
X
-
Y
- -
- Start -
-
-

You can download this example here.

- -

Mixed Transformations

-

The current specification does not support animating different transform properties with multiple tween objects at the same time, you must stack them all together into a single object. See the example below:

- -
var tween1 = KUTE.fromTo('selector1',{rotateX:0},{rotateX:20}).start();
-var tween2 = KUTE.fromTo('selector1',{skewY:0},{skewY:45}).start();
-
-

If you check the test here, you will notice that only the skewY is going to work and no rotation. Now let's do this properly.

- -
var tween1 = KUTE.fromTo(
-	'selector1', // element
-	{translateX:0, rotateX:0, rotateY:0, rotateZ:0}, // from
-	{translateX:250, rotateX:360, rotateY:15, rotateZ:5}, // to
-	{perspective:400, perspectiveOrigin: 'center top'} // transform options
-);
-var tween2 = KUTE.fromTo(
-	'selector2', // element
-	{translateX:0, rotateX:0, rotateY:0, rotateZ:0}, // from values
-	{translateX:-250, rotateX:360, rotateY:15, rotateZ:5}, // to values
-	{parentPerspective:400, parentPerspectiveOrigin: 'center top'} // transform options
-);
-
-

Now you can see we are using the specific transform options, the first tween object uses these settings for an element and the second for its parent.

- -
-
element perspective 400px
-
parent perspective 400px
- -
- Start -
-
- -

This example also shows the difference between an element's perspective and a parent's perspective. You can download the above example here.

- -

Chained Transformations

-

KUTE.js has the ability to stack transform properties as they come in chained tweens because when we run animations one after another we are kinda expecting a certain degree of continuity. As explained before, the best solution is the .to() method because it has the ability to stack properties found in the element's inline styling, mostly from previous tween animation, and use them as start values for the next tween. It also transfers unchanged values to values end for that same reason. OK now, let's see a side by side comparison with 3 elements:

-
-
FROMTO
-
FROMTO
-
TO
- -
- Start -
-
-

What's this all about?

-
    -
  • the first box uses a regular .fromTo() object, we are doing things normally, we would expect them to work properly but due to the nature of the transforms, this is what it does
  • -
  • the second box is also using .fromTo() object, but using proper values for all tweens at all times, so we fixed that glitch
  • -
  • and the last box uses the .to() method, and does the chaining easier for most properties, especially for transform
  • -
- -

When coding transformation chains I would highly recommend:

-
    -
  • keep the same order of the transform properties, best would be: translation, rotation, skew and scale; an example of the difference shown here for rotations and here for rotations and skew;
  • -
  • 2D and 3D translations would work best in if you provide a value at all times; eg. translate:[x,y] and translate3d:[x,y,z]; for instance using translate:150 or translateX:150 would mean that all other axis are 0;
  • -
  • on larger amount of elements animating chains, the .fromTo() method is fastest, so you will have more work, but can potentially minimize or eliminate any syncronization issues that may occur, as explained in the features page;
  • -
  • download this example here.
  • -
- -

Box Model Properties

-

KUTE.js core engine supports most used box model properties, and almost all the box model properties via the CSS Plugin, so the next example will only animate width, height, top and left.

-
var tween1 = KUTE.to('selector1',{width:200});
-var tween2 = KUTE.to('selector1',{height:300});
-var tween3 = KUTE.to('selector1',{left:250});
-var tween4 = KUTE.to('selector1',{top:100});
-
-

We're gonna chain these tweens and start the animation. You can download this example here.

-
-
BOX MODEL
- -
- Start -
-
- - -

TIP: the width and height properties used together can be great for scale animation fallback on images for legacy browsers.

- -

Color Properties

-

The next example is about animating color properties. As for example, check these lines for reference. Additional color properties such as borderColor or borderLeftColor are supported via the CSS Plugin.

-
KUTE.to('selector1',{color:'rgb(0,66,99)'}).start();
-KUTE.to('selector1',{backgroundColor:'#069'}).start();
-KUTE.to('selector1',{backgroundColor:'turquoise'}).start(); // IE9+ only
-
-

Let's get some animation going. Download the example here.

- -
-
Colors
- -
- Start -
-
- -

A quick reminder: you can also use RGB or RGBA, but the last one is not supported on IE8 and it will fallback to RGB.

- -

Vertical Scrolling

-

Another property we can animate with KUTE.js is scrollTop. I works for both the window and any scrollable object. Quick example:

-
KUTE.to('selector',{scroll:450}).start(); // for a scrollable element
-KUTE.to('window',{scroll:450}).start(); // for the window
-
-

The scroll animation could however be influenced by mouse hover effects, usually creating some really nasty bottlenecks, but you can always add some CSS to your page to prevent that:

-
/* prevent scroll bottlenecks */
-body[data-tweening="scroll"],
-body[data-tweening="scroll"] * { pointer-events: none !important; }
-
-

A working example would work like this. Scroll works with IE8+ and is a unitless property even if these scroll distances are measured in pixels.

- - -

Cross Browser Animation Example

-

Unlike the examples hosted on Codepen, most examples here should be supported on legacy browsers. The next example is going to explain more details about how to target browsers according to their supported properties, so stick around. So, if your target audience uses legacy browsers in a significant percent, check to have the proper polyfills and also make sure you target your browsers, here's a complete reference. Now we are ready: - -

Collect Information And Cache It

-
// grab an HTML element to build a tween object for it 
-var element = document.getElementById("myElement");
-
-// check for IE legacy browsers
-var isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
-var isIE8 = isIE === 8;
-var isIE9 = isIE === 9;
-
-
-// most browsers have specific checks, so make sure 
-// you include all you need for your target audience
-
-
-

Define Properties And Options Objects

-
// create values and options objects
-var startValues = {};
-var endValues = {};
-var options = {};
-
-// here we define properties that are commonly supported
-startValues.backgroundColor = 'rgba(255,214,38,1)'; endValues.backgroundColor = 'rgba(236,30,113,0.1)';
-
-// here we define the properties according to the target browsers
-if (isIE8) { // or any other browser that doesn"t support transforms		
-	startValues.left = 0;
-	endValues.left = 250;
-	// for IE we override color values
-	startValues.backgroundColor = '#CDDC39'; 
-	endValues.backgroundColor = '#ec1e71';
-	// IE8 also doesn't support RGBA, we set to animate the opacity of the element
-	startValues.opacity = 1;
-	endValues.opacity = 0.2;
-} else if (isIE9) { // or any other browser that only support 2d transforms
-	startValues.translate = 0; // 2d translate on X axis
-	endValues.translate = 250;
-	startValues.rotate = -180; // 2d rotation on Z axis
-	endValues.rotate = 0;
-	startValues.scale = 1; // 2d scale
-	endValues.scale = 1.5;
-} else { // most modern browsers
-	startValues.translate3d = [0,0,0]; //3d translation on X axis
-	endValues.translate3d = [250,0,0];				
-	startValues.rotateZ = -180; // 3d rotation on Z axis
-	endValues.rotateZ = 0;
-	startValues.rotateX = -20; // 3d rotation on X axis
-	endValues.rotateX = 0;				
-	startValues.scale = 1; // 2d scale
-	endValues.scale = 1.5;
-	options.perspective = 400; // 3d transform option
-}
-
-// common tween options
-options.easing = "easingCubicOut";
-options.duration = 2500;
-options.yoyo = true;
-options.repeat = 1;
-
- -

Build Tween Object And Tween Controls

-
// the cached object
-var myTween = KUTE.fromTo(element, startValues, endValues, options);
-
-// trigger buttons
-var startButton = document.getElementById('startButton'),
-	stopButton = document.getElementById('stopButton'),
-	playPauseButton = document.getElementById('playPauseButton');
-
-// add handlers for the trigger buttons
-startButton.addEventListener('click', function(e){
-	e.preventDefault();
-	if (!myTween.playing) { myTween.start(); } // only start the animation if hasn't started yet
-}, false);
-stopButton.addEventListener('click', function(e){
-	e.preventDefault();
-	if (myTween.playing) { myTween.stop(); } // only stop the animation if there is any
-}, false);
-playPauseButton.addEventListener('click', function(e){
-	e.preventDefault();	
-	if (!myTween.paused && myTween.playing) { 
-		myTween.pause(); playPauseButton.innerHTML = 'Resume';
-	} else { 
-		myTween.resume(); 
-		playPauseButton.innerHTML = 'Pause';
-	}  
-}, false);
-
-

Live Demo

-
-
- -
-
- Pause - Start - Stop -
-
-

Let's explain this code a bit. KUTE.js gives you the internal variables myTween.playing and myTween.paused (both true/false) to help you easily manage the tween control methods all together as in this example here. As said before, KUTE.js version 0.9.5 doesn't stat animating by default, for all the examples on this page you have to start it yourself, unlike their versions hosted on Codepen.

-

Also please know that opacity animation only works on Internet Explorer 8 if the target element uses float: left/right, display: block or display: inline-block.

-
    -
  • the START button will use the .start() method and the animation starts;
  • -
  • the STOP button will use the .stop() method and stops the animation; after this the, animation can only be started again
  • -
  • the PAUSE button will use the .pause() method and pauses the animation; this also changes the button's text and functionality;
  • -
  • the RESUME button will use the .resume() method and resumes the animation; this reverses the button's initial state;
  • -
  • make sure you work with the conditions properly when you want to pause an animation you MUST check both !myTween.playing and myTween.paused conditions because you could end up with errors.
  • -
- -

Tween Object Collections

-

With KUTE.js 1.5.0 new tween object constructor methods were introduced, and they allow you to create a tween object for each element in a collection, a very handy way to ease and speed up the animation programing workflow. Let's have a little fun.

-
// a simple .to() for a collection of elements would look like this
-var myMultiTween1 = KUTE.allTo('selector1',{translate:[0,150]});
-
-// or a more complex .fromTo() example with the two new options
-var myMultiTween2 = KUTE.allFromTo(
-    'selector2',
-    {translate:[0,0], rotate: 0}, 
-    {translate:[0,150], rotate: 360}, 
-    {transformOrigin: '10% 10%', offset: 200 }
-);
-
-

And should looks like this:

-
-
K
-
U
-
T
-
E
- -
- Start -
-
-

As you can see, we also used the new tween options offset and transformOrigin and they make it so much more easy.

- - -

Easing Functions

-

KUTE.js core engine comes with Robert Penner's easing functions, but it can also work with any other easing functions, including custom functions. In the example below the first box animation uses the linear easing function and the second will use another function you choose.

-
-
Linear
-
- -
-
- Select -
    -
  • easingSinusoidalIn
  • -
  • easingSinusoidalOut
  • -
  • easingSinusoidalInOut
  • -
  • easingQuadraticIn
  • -
  • easingQuadraticOut
  • -
  • easingQuadraticInOut
  • -
  • easingCubicIn
  • -
  • easingCubicOut
  • -
  • easingCubicInOut
  • -
  • easingQuarticIn
  • -
  • easingQuarticOut
  • -
  • easingQuarticInOut
  • -
  • easingQuinticIn
  • -
  • easingQuinticOut
  • -
  • easingQuinticInOut
  • -
  • easingCircularIn
  • -
  • easingCircularOut
  • -
  • easingCircularInOut
  • -
  • easingExponentialIn
  • -
  • easingExponentialOut
  • -
  • easingExponentialInOut
  • -
  • easingBackIn
  • -
  • easingBackOut
  • -
  • easingBackInOut
  • -
  • easingElasticIn
  • -
  • easingElasticOut
  • -
  • easingElasticInOut
  • -
-
- Start -
-
-

For more examples and info about the other easing functions, head over to the easing examples page.

-
- - - - - - -
- - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + KUTE.js Core Engine Examples | Javascript Animation Engine + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+

Core Engine

+

KUTE.js core engine can animate by itself a great deal of CSS properties as well as scroll. You can do it all with native Javascript or with jQuery, but before we head over to the more advanced examples, let's have a quick look at these two + basic examples here. Note: the examples are posted on codepen.

+ +

Basic Native Javascript Example

+

When developing with native Javascript, a very basic syntax goes like this:

+ +
+// this is the tween object, basically KUTE.method(element, from, to, options);
+var tween = KUTE.fromTo('selector', {left: 0}, {left: 100}, {yoyo: true});
+
+ +

Now the tween object is created, it's a good time for you to know that via Native Javascript we always animate the first HTML element only, even if you're using a class selector. To create/control a tween for multiple elements + such as querySelectorAll() or getElementsByTagName(), you need to do a for () loop, or make use of the two new methods: .allTo() or .allFromTo(). Now let's apply the tween + control methods:

+ +
tween.start(); // starts the animation
+tween.stop(); // stops current tween and all chained tweens animating
+tween.pause(); // pauses current tween animation
+tween.play(); // or tween.resume(); resumes current tween animation
+tween.chain(tween2); // when tween animation finished, you can trigger the start of another tween
+tween.playing // checks if the tween is currenlty active so we prevent start() when not needed
+tween.paused // checks if the tween is currenlty active so we can prevent pausing or resume if needed
+
+ +

The demo for the above example is here.

+ +

Basic jQuery Example

+

KUTE.js includes a jQuery Plugin to help you easily implement KUTE.js in your jQuery applications. When using jQuery, the syntax is familiar but works a bit different than plain Javascript due to jQuery's specific code standards. Let's have + a look:

+
// this is the tween object, basically $('selector').method(fromValues, toValue, options)
+var tween = $('selector').fromTo({top: 20}, {top: 100}, {delay: 500});
+
+

We mentioned that the jQuery Plugin is different, and here's why: the above function call uses the allFromTo method to create an Array of objects for each HTML element of chosen selector, but if the selector + only returns one element the call returns a single tween object built with fromTo method. For the array of objects we can now apply the exact same tween control methods, except these:

+
tween.length // check if the tween is an array of objects
+tween.length && tween.tweens[0].playing && tween.tweens[tween.length-1].playing // now we know that one of the tweens is playing
+tween.length && tween.tweens[0].paused && tween.tweens[tween.length-1].paused // now we know that one of the tweens is paused
+
+ +

The demo for the above example is here.

+ +

Transform Properties Examples

+

KUTE.js supports almost all about transform as described in the spec: the 2D translate, rotate, skewX, skewY and scale, as well as the 3D translateX, translateY, translateZ, translate3d, rotateX, rotateY, rotateZ properties. Additionally it + allows you to set a perspective for the element or it's parent as well as a perpective-origin for the element or it's parent.

+ +

Translations

+

In the next example the first box is moving to left 250px with translate property, the second box is moving to the right by 200px using translateX and the third box is moving to the bottom using translate3d. + The last box also uses translate3d but requires a perspective value for the animation on the Z axis to be effective.

+
var tween1 = KUTE.fromTo('selector1',{translate:0},{translate:-250}); // or translate:[x,y] for both axis
+var tween2 = KUTE.fromTo('selector2',{translateX:0},{translateX:200});
+var tween3 = KUTE.fromTo('selector3',{translate3d:[0,0,0]},{translate3d:[0,100,0]});
+var tween4 = KUTE.fromTo('selector4',{translate3d:[0,0,0]},{translate3d:[0,0,-100]},{parentPerspective: 100});
+
+

And here is how it looks like:

+
+
2D
+
X
+
Y
+
Z
+ +
+ Start +
+
+ +

As you can see in your browsers console, for all animations translate3d is used, as explained in the features page. Also the first example that's using the 2D translate for both vertical + and horizontal axis even if we only set X axis. You can download this example here.

+

Remember: stacking translate and translate3d together may not work and IE9 does not support perspective.

+ +

Rotations

+

Next we're gonna animate 4 elements with one axis each element. Unlike translations, KUTE.js does not support rotate3d.

+ +
var tween1 = KUTE.fromTo('selector1',{rotate:0},{rotate:-720});
+var tween2 = KUTE.fromTo('selector2',{rotateX:0},{rotateX:200});
+var tween3 = KUTE.fromTo('selector3',{rotateY:0},{rotateY:160},{perspective:100});
+var tween4 = KUTE.fromTo('selector4',{rotateZ:0},{rotateZ:360});
+
+ +

And here is how it looks like:

+
+
2D
+
X
+
Y
+
Z
+
+ Start +
+
+

The rotateX and rotateY are 3D based rotations, so they require a perspective in order to make the browser render proper 3D layers, but in the example they animate different because only the second, Y axis, uses a + perspective setting. The rotation on Z axis does not require a perspective. Unlike translations, you can stack all axis rotation for your animation, but we will see that in a later example. You can download this example here.

+ +

Skews

+

KUTE.js supports skewX and skewY so let's animate the two. Since they are 2D transformations, IE9 supports skews.

+
var tween1 = KUTE.fromTo('selector1',{skewX:0},{skewX:20});
+var tween2 = KUTE.fromTo('selector2',{skewY:0},{skewY:45});
+
+ +

And here is how it looks like:

+
+
X
+
Y
+ +
+ Start +
+
+

You can download this example here.

+ +

Mixed Transformations

+

The current specification does not support animating different transform properties with multiple tween objects at the same time, you must stack them all together into a single object. See the example below:

+ +
var tween1 = KUTE.fromTo('selector1',{rotateX:0},{rotateX:20}).start();
+var tween2 = KUTE.fromTo('selector1',{skewY:0},{skewY:45}).start();
+
+

If you check the test here, you will notice that only the skewY is going to work and no rotation. Now let's do this properly.

+ +
var tween1 = KUTE.fromTo(
+  'selector1', // element
+  {translateX:0, rotateX:0, rotateY:0, rotateZ:0}, // from
+  {translateX:250, rotateX:360, rotateY:15, rotateZ:5}, // to
+  {perspective:400, perspectiveOrigin: 'center top'} // transform options
+);
+var tween2 = KUTE.fromTo(
+  'selector2', // element
+  {translateX:0, rotateX:0, rotateY:0, rotateZ:0}, // from values
+  {translateX:-250, rotateX:360, rotateY:15, rotateZ:5}, // to values
+  {parentPerspective:400, parentPerspectiveOrigin: 'center top'} // transform options
+);
+
+

Now you can see we are using the specific transform options, the first tween object uses these settings for an element and the second for its parent.

+ +
+
element perspective 400px
+
parent perspective 400px
+ +
+ Start +
+
+ +

This example also shows the difference between an element's perspective and a parent's perspective. You can download the above example here.

+ +

Chained Transformations

+

KUTE.js has the ability to stack transform properties as they come in chained tweens because when we run animations one after another we are kinda expecting a certain degree of continuity. As explained before, the best solution is the .to() method because it has the ability to stack properties found in the element's inline styling, mostly from previous tween animation, and use them as start values for the next tween. It also transfers unchanged values to + values end for that same reason. OK now, let's see a side by side comparison with 3 elements:

+
+
FROMTO
+
FROMTO
+
TO
+ +
+ Start +
+
+

What's this all about?

+
    +
  • the first box uses a regular .fromTo() object, we are doing things normally, we would expect them to work properly but due to the nature of the transforms, this is what it does
  • +
  • the second box is also using .fromTo() object, but using proper values for all tweens at all times, so we fixed that glitch
  • +
  • and the last box uses the .to() method, and does the chaining easier for most properties, especially for transform
  • +
+ +

When coding transformation chains I would highly recommend:

+
    +
  • keep the same order of the transform properties, best would be: translation, rotation, skew and scale; an example of the difference shown here for rotations and + here for rotations and skew;
  • +
  • 2D and 3D translations would work best in if you provide a value at all times; eg. translate:[x,y] and translate3d:[x,y,z]; for instance using translate:150 or translateX:150 would mean + that all other axis are 0;
  • +
  • on larger amount of elements animating chains, the .fromTo() method is fastest, so you will have more work, but can potentially minimize or eliminate any syncronization issues that may occur, as explained in the features page;
  • +
  • download this example here.
  • +
+ +

Box Model Properties

+

KUTE.js core engine supports most used box model properties, and almost all the box model properties via the CSS Plugin, so the next example will only animate width, height, top and left.

+
var tween1 = KUTE.to('selector1',{width:200});
+var tween2 = KUTE.to('selector1',{height:300});
+var tween3 = KUTE.to('selector1',{left:250});
+var tween4 = KUTE.to('selector1',{top:100});
+
+

We're gonna chain these tweens and start the animation. You can download this example here.

+
+
BOX MODEL
+ +
+ Start +
+
+ + +

TIP: the width and height properties used together can be great for scale animation fallback on images for legacy browsers.

+ +

Color Properties

+

The next example is about animating color properties. As for example, check these lines for reference. Additional color properties such as borderColor or borderLeftColor are supported via the CSS Plugin.

+
KUTE.to('selector1',{color:'rgb(0,66,99)'}).start();
+KUTE.to('selector1',{backgroundColor:'#069'}).start();
+KUTE.to('selector1',{backgroundColor:'turquoise'}).start(); // IE9+ only
+
+

Let's get some animation going. Download the example here.

+ +
+
Colors
+ +
+ Start +
+
+ +

A quick reminder: you can also use RGB or RGBA, but the last one is not supported on IE8 and it will fallback to RGB.

+ +

Vertical Scrolling

+

Another property we can animate with KUTE.js is scrollTop. I works for both the window and any scrollable object. Quick example:

+
KUTE.to('selector',{scroll:450}).start(); // for a scrollable element
+KUTE.to('window',{scroll:450}).start(); // for the window
+
+

The scroll animation could however be influenced by mouse hover effects, usually creating some really nasty bottlenecks, but you can always add some CSS to your page to prevent that:

+
/* prevent scroll bottlenecks */
+body[data-tweening="scroll"],
+body[data-tweening="scroll"] * { pointer-events: none !important; }
+
+

A working example would work like this. Scroll works with IE8+ and is a unitless property even if these scroll distances are measured in pixels.

+ + +

Cross Browser Animation Example

+

Unlike the examples hosted on Codepen, most examples here should be supported on legacy browsers. The next example is going to explain more details about how to target browsers + according to their supported properties, so stick around. So, if your target audience uses legacy browsers in a significant percent, check to have the proper polyfills and also make sure you target your browsers, here's a + complete reference. Now we are ready: + +

Collect Information And Cache It

+
// grab an HTML element to build a tween object for it
+var element = document.getElementById("myElement");
+
+// check for IE legacy browsers
+var isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
+var isIE8 = isIE === 8;
+var isIE9 = isIE === 9;
+
+
+// most browsers have specific checks, so make sure
+// you include all you need for your target audience
+
+
+

Define Properties And Options Objects

+
// create values and options objects
+var startValues = {};
+var endValues = {};
+var options = {};
+
+// here we define properties that are commonly supported
+startValues.backgroundColor = 'rgba(255,214,38,1)'; endValues.backgroundColor = 'rgba(236,30,113,0.1)';
+
+// here we define the properties according to the target browsers
+if (isIE8) { // or any other browser that doesn"t support transforms
+  startValues.left = 0;
+  endValues.left = 250;
+  // for IE we override color values
+  startValues.backgroundColor = '#CDDC39';
+  endValues.backgroundColor = '#ec1e71';
+  // IE8 also doesn't support RGBA, we set to animate the opacity of the element
+  startValues.opacity = 1;
+  endValues.opacity = 0.2;
+} else if (isIE9) { // or any other browser that only support 2d transforms
+  startValues.translate = 0; // 2d translate on X axis
+  endValues.translate = 250;
+  startValues.rotate = -180; // 2d rotation on Z axis
+  endValues.rotate = 0;
+  startValues.scale = 1; // 2d scale
+  endValues.scale = 1.5;
+} else { // most modern browsers
+  startValues.translate3d = [0,0,0]; //3d translation on X axis
+  endValues.translate3d = [250,0,0];
+  startValues.rotateZ = -180; // 3d rotation on Z axis
+  endValues.rotateZ = 0;
+  startValues.rotateX = -20; // 3d rotation on X axis
+  endValues.rotateX = 0;
+  startValues.scale = 1; // 2d scale
+  endValues.scale = 1.5;
+  options.perspective = 400; // 3d transform option
+}
+
+// common tween options
+options.easing = "easingCubicOut";
+options.duration = 2500;
+options.yoyo = true;
+options.repeat = 1;
+
+ +

Build Tween Object And Tween Controls

+
// the cached object
+var myTween = KUTE.fromTo(element, startValues, endValues, options);
+
+// trigger buttons
+var startButton = document.getElementById('startButton'),
+  stopButton = document.getElementById('stopButton'),
+  playPauseButton = document.getElementById('playPauseButton');
+
+// add handlers for the trigger buttons
+startButton.addEventListener('click', function(e){
+  e.preventDefault();
+  if (!myTween.playing) { myTween.start(); } // only start the animation if hasn't started yet
+}, false);
+stopButton.addEventListener('click', function(e){
+  e.preventDefault();
+  if (myTween.playing) { myTween.stop(); } // only stop the animation if there is any
+}, false);
+playPauseButton.addEventListener('click', function(e){
+  e.preventDefault();
+  if (!myTween.paused && myTween.playing) {
+    myTween.pause(); playPauseButton.innerHTML = 'Resume';
+  } else {
+    myTween.resume();
+    playPauseButton.innerHTML = 'Pause';
+  }
+}, false);
+
+

Live Demo

+
+
+ +
+
+ Pause + Start + Stop +
+
+

Let's explain this code a bit. KUTE.js gives you the internal variables myTween.playing and myTween.paused (both true/false) to help you easily manage the tween control methods all together as in this example + here. As said before, KUTE.js version 0.9.5 doesn't stat animating by default, for all the examples on this page you have to start it yourself, unlike their versions hosted on Codepen.

+

Also please know that opacity animation only works on Internet Explorer 8 if the target element uses float: left/right, display: block or display: inline-block.

+
    +
  • the START button will use the .start() method and the animation starts;
  • +
  • the STOP button will use the .stop() method and stops the animation; after this the, animation can only be started again
  • +
  • the PAUSE button will use the .pause() method and pauses the animation; this also changes the button's text and functionality;
  • +
  • the RESUME button will use the .resume() method and resumes the animation; this reverses the button's initial state;
  • +
  • make sure you work with the conditions properly when you want to pause an animation you MUST check both !myTween.playing and myTween.paused conditions because you could end up with errors.
  • +
+ +

Tween Object Collections

+

With KUTE.js 1.5.0 new tween object constructor methods were introduced, and they allow you to create a tween object for each element in a collection, a very handy way to ease and speed up the animation programing workflow. Let's have + a little fun.

+
// a simple .to() for a collection of elements would look like this
+var myMultiTween1 = KUTE.allTo('selector1',{translate:[0,150]});
+
+// or a more complex .fromTo() example with the two new options
+var myMultiTween2 = KUTE.allFromTo(
+    'selector2',
+    {translate:[0,0], rotate: 0},
+    {translate:[0,150], rotate: 360},
+    {transformOrigin: '10% 10%', offset: 200 }
+);
+
+

And should looks like this:

+
+
K
+
U
+
T
+
E
+ +
+ Start +
+
+

As you can see, we also used the new tween options offset and transformOrigin and they make it so much more easy.

+ + +

Easing Functions

+

KUTE.js core engine comes with Robert Penner's easing functions, but it can also work with any other easing functions, including custom functions. In the example below the first box animation uses the linear easing function + and the second will use another function you choose.

+
+
Linear
+
+ +
+
+ Select +
    +
  • easingSinusoidalIn
  • +
  • easingSinusoidalOut
  • +
  • easingSinusoidalInOut
  • +
  • easingQuadraticIn
  • +
  • easingQuadraticOut
  • +
  • easingQuadraticInOut
  • +
  • easingCubicIn
  • +
  • easingCubicOut
  • +
  • easingCubicInOut
  • +
  • easingQuarticIn
  • +
  • easingQuarticOut
  • +
  • easingQuarticInOut
  • +
  • easingQuinticIn
  • +
  • easingQuinticOut
  • +
  • easingQuinticInOut
  • +
  • easingCircularIn
  • +
  • easingCircularOut
  • +
  • easingCircularInOut
  • +
  • easingExponentialIn
  • +
  • easingExponentialOut
  • +
  • easingExponentialInOut
  • +
  • easingBackIn
  • +
  • easingBackOut
  • +
  • easingBackInOut
  • +
  • easingElasticIn
  • +
  • easingElasticOut
  • +
  • easingElasticInOut
  • +
+
+ Start +
+
+

For more examples and info about the other easing functions, head over to the easing examples page.

+
+ + + + + + +
+ + + + + + + + + + + + + + + + + + + + diff --git a/demo/extend.html b/demo/extend.html index 4647cb4..e602209 100644 --- a/demo/extend.html +++ b/demo/extend.html @@ -3,7 +3,9 @@ - + + + @@ -12,82 +14,81 @@ - + Extending KUTE.js | Javascript Animation Engine - + - + - + - - - + + + - - - - - + + + + + -
- -
- - +
-
- -

Extend Guide

-

KUTE.js is a very flexible animation engine that allows you to extend beyond measure. In this tutorial we'll dig into what's best to do to extend/customize the functionality of KUTE.js core, plugins and features.

+
-

Basic Plugin Template

-

The best way to extend, no matter what you would like to achieve is to use a specific closure, here's an example:

-
/* KUTE.js - The Light Tweening Engine
+        
+
+        
+ +

Extend Guide

+

KUTE.js is a very flexible animation engine that allows you to extend beyond measure. In this tutorial we'll dig into what's best to do to extend/customize the functionality of KUTE.js core, plugins and features.

+ +

Basic Plugin Template

+

The best way to extend, no matter what you would like to achieve is to use a specific closure, here's an example:

+
/* KUTE.js - The Light Tweening Engine
  * by dnp_theme
  * package - pluginName
  * desc - what your plugin does
@@ -100,25 +101,25 @@
     define(['kute.js'], factory);
   } else if(typeof module == 'object' && typeof require == 'function') {
     module.exports = factory(require('kute.js'));
-  } else if ( typeof root.KUTE !== 'undefined' ) {	
+  } else if ( typeof root.KUTE !== 'undefined' ) {
     factory(root.KUTE);
   } else {
     throw new Error("pluginName require KUTE.js.");
   }
 }(this, function (KUTE) {
     // your code goes here
-    
+
     // in this function body
-    
+
     // the plugin returns this
     return this;
 }));
 
-

As suggested in the above template, your function body could be written with one or more of the examples below.

- -

Extend Tween Control

-

In some cases, you may want to extend with additional tween control methods, so before you do that, make sure to check Tween function to get the internal references notation:

-
//add a reference to _tween function
+            

As suggested in the above template, your function body could be written with one or more of the examples below.

+ +

Extend Tween Control

+

In some cases, you may want to extend with additional tween control methods, so before you do that, make sure to check Tween function to get the internal references notation:

+
//add a reference to _tween function
 var Tween = KUTE.Tween;
 
 // let's add a timescale method
@@ -155,28 +156,31 @@ Tween.prototype.restart = function(){
 
 // methods to queue callbacks with ease
 Tween.prototype.onUpdate = function(){
-    this.options.update = arguments; 
+    this.options.update = arguments;
     return this;
 }
 
 
-

For some reasons these methods aren't included into the core/plugins by default, but let you decide what you need and how to customize the animation engine for your very specific need.

- -

Support For Additional CSS Properties

-

KUTE.js core engine and plugins cover what I consider to be most essential for animation, but you may have a different opinion. In case you may want to know how to animate properties that are not currently supported, stick to this guide and you'll master it real quick, it's very easy.

-

We need basically 3 functions:

-
    -
  • KUTE.prepareStart['propertyName'] required a function to get the current value of the property required for the .to() method;
  • -
  • KUTE.parseProperty['propertyName'] required a function to process the user value / current value to have it ready to tween;
  • -
  • KUTE.dom['propertyName'] required a domUpdate function that will update the property value into the DOM;
  • -
  • KUTE.crossCheck['propertyName'] optional a function to help you set proper values when for instance startValues unit is different than endValues unit; so far this is used for CSS3/SVG transforms and SVG Morph, but it can be extended for many properties such as box-model properties or border-radius properties;
  • -
  • also optional additional functions that will help with value processing.
  • -
-

So let's add support for boxShadow! It should be a medium difficulty guide most developers can follow and the purpose of this guide is to showcase how easy it actually is to extend KUTE.js. So grab the above template and let's break it down to pieces:

-
// add a reference to global and KUTE object
-var g = typeof global !== 'undefined' ? global : window, K = KUTE, 
+            

For some reasons these methods aren't included into the core/plugins by default, but let you decide what you need and how to customize the animation engine for your very specific need.

+ +

Support For Additional CSS Properties

+

KUTE.js core engine and plugins cover what I consider to be most essential for animation, but you may have a different opinion. In case you may want to know how to animate properties that are not currently supported, stick to this guide and + you'll master it real quick, it's very easy.

+

We need basically 3 functions:

+
    +
  • KUTE.prepareStart['propertyName'] required a function to get the current value of the property required for the .to() method;
  • +
  • KUTE.parseProperty['propertyName'] required a function to process the user value / current value to have it ready to tween;
  • +
  • KUTE.dom['propertyName'] required a domUpdate function that will update the property value into the DOM;
  • +
  • KUTE.crossCheck['propertyName'] optional a function to help you set proper values when for instance startValues unit is different than endValues unit; so far this is used for CSS3/SVG transforms + and SVG Morph, but it can be extended for many properties such as box-model properties or border-radius properties;
  • +
  • also optional additional functions that will help with value processing.
  • +
+

So let's add support for boxShadow! It should be a medium difficulty guide most developers can follow and the purpose of this guide is to showcase how easy it actually is to extend KUTE.js. So grab the above template + and let's break it down to pieces:

+
// add a reference to global and KUTE object
+var g = typeof global !== 'undefined' ? global : window, K = KUTE,
     // add a reference to KUTE utilities
-    prepareStart = K.prepareStart, getCurrentStyle = K.getCurrentStyle, 
+    prepareStart = K.prepareStart, getCurrentStyle = K.getCurrentStyle,
     property = K.property, parseProperty = K.parseProperty, trueColor = K.truC,
     DOM = K.dom, color = g.Interpolate.color, unit = g.Interpolate.unit; // interpolation functions
 
@@ -189,8 +193,8 @@ var colRegEx = /(\s?(?:#(?:[\da-f]{3}){1,2}|rgba?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}
 // for browsers that don't support the property, use a filter
 // if (!(_boxShadow in document.body.style)) {return;}
 
-

Now we have access to the KUTE object, prototypes and it's utility functions, let's write a prepareStart function that will read the current boxShadow value:

-
// for the .to() method, you need to prepareStart the boxShadow property
+            

Now we have access to the KUTE object, prototypes and it's utility functions, let's write a prepareStart function that will read the current boxShadow value:

+
// for the .to() method, you need to prepareStart the boxShadow property
 // which means you need to read the current computed value
 // if the current computed value is not acceptable, use a default value
 prepareStart['boxShadow'] = function(property,value){
@@ -204,13 +208,14 @@ prepareStart['boxShadow'] = function(property,value){
 
 // also to read the current value of an attribute, replace first line of the above function body with this
 // var attrValue = element.getAttribute(property);
-// and return the value or a default value, mostly rgb(0,0,0) for colors, 1 for opacity, or 0 for most other types  
+// and return the value or a default value, mostly rgb(0,0,0) for colors, 1 for opacity, or 0 for most other types
 
-

Since KUTE.js 1.6.0, the tween object is bound to all property parsing utilities, meaning that you have access to this that has the target element, options, start and end values and everything else. This is extremely useful if you want to optimize and/or extend particular properties values, the dom update functions, and even override the property name

+

Since KUTE.js 1.6.0, the tween object is bound to all property parsing utilities, meaning that you have access to this that has the target element, options, start and end values and everything else. This is extremely useful if + you want to optimize and/or extend particular properties values, the dom update functions, and even override the property name

-

Now we need an utility function that makes sure the structure looks right for the DOM update function.

-
// utility function to process values accordingly
+            

Now we need an utility function that makes sure the structure looks right for the DOM update function.

+
// utility function to process values accordingly
 // numbers must be floats/integers and color must be rgb object
 var processBoxShadowArray = function(shadow){
   var newShadow;
@@ -220,44 +225,45 @@ var processBoxShadowArray = function(shadow){
   } else if (shadow.length === 4) { // [h-shadow, v-shadow, color, inset] | [h-shadow, v-shadow, blur, color]
     newShadow = /inset|none/.test(shadow[3]) ? [shadow[0], shadow[1], 0, 0, shadow[2], shadow[3]] : [shadow[0], shadow[1], shadow[2], 0, shadow[3], 'none'];
   } else if (shadow.length === 5) { // [h-shadow, v-shadow, blur, color, inset] | [h-shadow, v-shadow, blur, spread, color]
-    newShadow = /inset|none/.test(shadow[4]) ? [shadow[0], shadow[1], shadow[2], 0, shadow[3], shadow[4]] : [shadow[0], shadow[1], shadow[2], shadow[3], shadow[4], 'none'];           
+    newShadow = /inset|none/.test(shadow[4]) ? [shadow[0], shadow[1], shadow[2], 0, shadow[3], shadow[4]] : [shadow[0], shadow[1], shadow[2], shadow[3], shadow[4], 'none'];
   } else if (shadow.length === 6) { // ideal [h-shadow, v-shadow, blur, spread, color, inset]
-    newShadow = shadow; 
-  } 
+    newShadow = shadow;
+  }
 
   // make sure the numbers are ready to tween
   for (var i=0; i<4; i++){
-    newShadow[i] = parseFloat(newShadow[i]);  
+    newShadow[i] = parseFloat(newShadow[i]);
   }
   // make sure color is an rgb object
   newShadow[4] = trueColor(newShadow[4]); // where K.truC()/trueColor is a core method to return the true color in rgb object format
   return newShadow;
 };
-
+
-

Next we'll need to write a parseProperty function that will prepare the property value and build an Object or Array of values ready to tween. This function also registers the KUTE.dom['boxShadow'] function into the KUTE object, and this way we avoid filling the main object with unnecessary functions, just to keep performance tight.

- -
// the parseProperty for boxShadow 
-// registers the window.dom['boxShadow'] function 
+            

Next we'll need to write a parseProperty function that will prepare the property value and build an Object or Array of values ready to tween. This function also registers the KUTE.dom['boxShadow'] function into the + KUTE object, and this way we avoid filling the main object with unnecessary functions, just to keep performance tight.

+ +
// the parseProperty for boxShadow
+// registers the window.dom['boxShadow'] function
 // returns an array of 6 values in the following format
 // [horizontal, vertical, blur, spread, color: {r:0,g:0,b:0}, inset]
 parseProperty['boxShadow'] = function(property,value,element){
   // the DOM update function for boxShadow registers here
   // we only enqueue it if the boxShadow property is used to tween
   if ( !('boxShadow' in DOM) ) {
-    DOM['boxShadow'] = function(element,property,startValue,endValue,progress) { // element, propertyName, valuesStart.boxShadow, valuesEnd.boxShadow, progress 
+    DOM['boxShadow'] = function(element,property,startValue,endValue,progress) { // element, propertyName, valuesStart.boxShadow, valuesEnd.boxShadow, progress
 
       // let's start with the numbers | set unit | also determine inset
       var numbers = [], px = 'px', // the unit is always px
-        inset = startValue[5] !== 'none' || endValue[5] !== 'none' ? ' inset' : false; 
+        inset = startValue[5] !== 'none' || endValue[5] !== 'none' ? ' inset' : false;
 
-      for (var i=0; i<4; i++){ // for boxShadow coordinates we do the math for an array of numbers 
+      for (var i=0; i<4; i++){ // for boxShadow coordinates we do the math for an array of numbers
         numbers.push( unit(startValue[i], endValue[i], px, progress) );
       }
 
       // now we handle the color
       var colorValue = color(startValue[4],endValue[4],progress);
-      
+
       // last piece of the puzzle, the DOM update
       element.style[_boxShadow] = inset ? colorValue + numbers.join(' ') + inset : colorValue + numbers.join(' ');
     };
@@ -271,9 +277,9 @@ parseProperty['boxShadow'] = function(property,value,element){
     value = /inset/.test(value) ? value.replace(/(\s+inset|inset+\s)/g,'') : value;
 
     // also getComputedStyle often returns color first "rgb(0, 0, 0) 15px 15px 6px 0px inset"
-    shadowColor = value.match(colRegEx); 
+    shadowColor = value.match(colRegEx);
     value = value.replace(shadowColor[0],'').split(' ').concat([shadowColor[0].replace(/\s/g,'')],[inset]);
-    
+
     // now we can use the above specific utitlity
     value = processBoxShadowArray(value);
   } else if (value instanceof Array){
@@ -283,8 +289,8 @@ parseProperty['boxShadow'] = function(property,value,element){
 }
 
-

And now, we are ready to tween both .to() and .fromTo() methods:

-
// tween to a string value
+            

And now, we are ready to tween both .to() and .fromTo() methods:

+
// tween to a string value
 var myBSTween1 = KUTE.to('selector', {boxShadow: '15px 25px #069'}).start();
 
 // or a fromTo with string and array, hex and rgb
@@ -293,66 +299,79 @@ var myBSTween2 = KUTE.fromTo('selector', {boxShadow: [15, 25, 0, '#069']}, {boxS
 // maybe you want to animate an inset boxShadow?
 var myBSTween3 = KUTE.fromTo('selector', {boxShadow: [5, 5, 0, '#069', 'inset']}, {boxShadow: '0px 0px rgb(0,0,0)'}).start();
 
-

You are now ready to demo!

-
-
- -
- Start -
-
-

This plugin should be compatible with IE9+ and anything that supports boxShadow CSS property. As you can see it can handle pretty much anything you throw at it, but it requires at least 3 values: h-shadow, v-shadow, and color because Safari doesn't work without a color. Also this plugin won't be able to handle multiple instances of boxShadow for same element, because the lack of support on legacy browsers, also the color cannot be RGBA, but hey, it supports both outline and inset shadows and you can fork it anyway to your liking.

-

If you liked this tutorial, feel free to write your own, a great idea would be for textShadow, it's very similar to the above example plugin.

- -

Utility Methods

-
    -
  • KUTE.selector(selector,multi) is the selector utility that uses getElementById or querySelector when multi argument is null or false, BUT when true, querySelectorAll is used and returns a HTMLCollection object.
  • -
  • KUTE.property(propertyName) is the autoPrefix function that returns the property with the right vendor prefix, but only if required; on legacy browsers that don't support the property, the function returns undefinedPropertyName and that would be an easy way to detect support for that property on most legacy browsers:
    if (/undefined/.test(KUTE.property('propertyName')) ) { /* legacy browsers */ } else { /* modern browsers */ }
  • -
  • KUTE.getPrefix() returns a vendor preffix even if the browser supports a specific preffixed property or not.
  • -
  • KUTE.getCurrentStyle(element,property) a hybrid getComputedStyle function to get the current value of the property required for the .to() method; it actually checks in element.style, element.currentStyle and window.getComputedStyle(element,null) to make sure it won't miss the property value;
  • -
  • KUTE.truD(value) a function that accepts String and Number and returns a {v: 150, u: 'px'} object for any box model or a single numeric value based property and make it ready to tween. When a second parameter is set to true it will return an object with value and unit specific for rotation angles and skews.
  • -
  • KUTE.truC(color) a function that returns an {r: 150, g: 150, b: 0} color object ready to tween; if the color value is a web safe color, the IE9+ browsers will be able to return the rgb object we need.
  • -
  • KUTE.htr(hex) a function that accepts HEX formatted colors and returns an {r: 150, g: 150, b: 0} color object;
  • -
  • KUTE.rth(r,g,b) a function that accepts numeric values for red, blue and green and returns a HEX format #006699 color string.
  • -
  • Interpolate.number is most essential interpolation tool when developing plugins for various properties not supported in the core.
  • -
  • Interpolate.unit is used mainly for box model properties, text properties, and generally anything that's a string based valued. Like width: 250px
  • -
  • Interpolate.color is a very fast interpolation function for colors, as used in the above example.
  • -
  • Interpolate.coords is SVG Plugin only, but you can have a look anytime when you're out of ideas.
  • -
+

You are now ready to demo!

+
+
- - -
- - - +
+ Start +
+
+

This plugin should be compatible with IE9+ and anything that supports boxShadow CSS property. As you can see it can handle pretty much anything you throw at it, but it requires at least 3 values: h-shadow, v-shadow, and color + because Safari doesn't work without a color. Also this plugin won't be able to handle multiple instances of boxShadow for same element, because the lack of support on legacy browsers, also the color cannot be RGBA, but hey, + it supports both outline and inset shadows and you can fork it anyway to your liking.

+

If you liked this tutorial, feel free to write your own, a great idea would be for textShadow, it's very similar to the above example plugin.

-
- +

Utility Methods

+
    +
  • KUTE.selector(selector,multi) is the selector utility that uses getElementById or querySelector when multi argument is null or false, BUT + when true, querySelectorAll is used and returns a HTMLCollection object.
  • +
  • KUTE.property(propertyName) is the autoPrefix function that returns the property with the right vendor prefix, but only if required; on legacy browsers that don't support the property, the function + returns undefinedPropertyName and that would be an easy way to detect support for that property on most legacy browsers:
    if (/undefined/.test(KUTE.property('propertyName')) ) { /* legacy browsers */ } else { /* modern browsers */ }
  • +
  • KUTE.getPrefix() returns a vendor preffix even if the browser supports a specific preffixed property or not.
  • +
  • KUTE.getCurrentStyle(element,property) a hybrid getComputedStyle function to get the current value of the property required for the .to() method; it actually checks in element.style, + element.currentStyle and window.getComputedStyle(element,null) to make sure it won't miss the property value;
  • +
  • KUTE.truD(value) a function that accepts String and Number and returns a {v: 150, u: 'px'} object for any box model or a single numeric value based property and make it ready to tween. When a second + parameter is set to true it will return an object with value and unit specific for rotation angles and skews.
  • +
  • KUTE.truC(color) a function that returns an {r: 150, g: 150, b: 0} color object ready to tween; if the color value is a web safe color, + the IE9+ browsers will be able to return the rgb object we need.
  • +
  • KUTE.htr(hex) a function that accepts HEX formatted colors and returns an {r: 150, g: 150, b: 0} color object;
  • +
  • KUTE.rth(r,g,b) a function that accepts numeric values for red, blue and green and returns a HEX format #006699 color string.
  • +
  • Interpolate.number is most essential interpolation tool when developing plugins for various properties not supported in the core.
  • +
  • Interpolate.unit is used mainly for box model properties, text properties, and generally anything that's a string based valued. Like width: 250px
  • +
  • Interpolate.color is a very fast interpolation function for colors, as used in the above example.
  • +
  • Interpolate.coords is SVG Plugin only, but you can have a look anytime when you're out of ideas.
  • +
+ + + +
+ + + + +
+ - - + - - + + - + - - - - + + + + + + + + + diff --git a/demo/features.html b/demo/features.html index dc3e312..a856f55 100644 --- a/demo/features.html +++ b/demo/features.html @@ -1,173 +1,203 @@ - - - - - - - - - - - - - - - - - KUTE.js Features | Javascript Animation Engine - - - - - - - - - - - - - - - - - - - -
- -
- - - -
-

Features Overview

-

Badass Performance

-

KUTE.js was developed with best practices in mind for fastest code execution and memory efficiency, but performance varies from case to case, as well as for all the other Javascript based animation engines. As a quick note on how it works, well for the most part values are cached for the entire duration of the animation so that the repetitive tasks run smoothly, uninterruptible and avoid layout thrashing. We all know the more properties used or the more elements to animate at the same time, the more power is required.

- -

Of course some would argue on many aspects, but we all trade something for the sake of something else, such as convenience and/or flexibility or fork a project that's already great to make it.. better. For the sake of performance or simply willing to provide a feature, some trade/neglect other elements such as syncronisation (check this video), code simplicity (lots of CSS for a custom animation) and more other.

-

To learn more about how performance can vary from case to case, check out this section, it's very informative.

-
- -
-

Extensible Prototype

-

KUTE.js already packs quite alot of features, and that is thanks to its flexible nature that allows you to easily extend to your heart's desire. Whether you like to extend with CSS properties, easing functions, HTML presentation attributes or anything that Javascript can touch, even if it's not possible with CSS transitions or other Javascript libraries, KUTE.js makes it super easy.

-

For instance if you want to be able to animate the filter property, you only need three functions: one for preparing the property values needed for tween object build-up, a second function to read current value and the last one for the DOM update callback, everything else is nicely taken care of. KUTE.js also provides very useful utilities for processing strings, HEX/RGBA colors and other tools you can use for your own plugin's processing.

-

You may want to head over to the extend page for an indepth guide on how to write your own plugin/extension.

-
- -
-

Auto Browser Prefix

-

KUTE.js uses a simple function to determine the vendor prefix and checks if the prefix is required. In any case it caches the prefixed/unprefixed property name in a variable to make it available when needed. This applies to the following CSS3 properties: transform, perspective, perspective-origin, border-radius and the requestAnimationFrame Javascript method.

-

We aren't only targeting properly browsers for CSS3 styling, but also increase performance because we don't need to update the styling on every frame for all browsers (and their versions) at once, just the right and only one; less string concatenation = more performance. This asumes you are NOT styling the above CSS3 properties using your stylesheets to avoid glitches with legacy browsers.

-

This feature is useful mostly for Safari, older Firefox and Opera versions and Internet Explorer 9.

-
- -
-

Browser Compatibility

-

KUTE.js covers all modern browsers but also provides fallback options for legacy browsers. The prefix free feature mentioned above is one way to enable smooth Javascript based animations on older versions Gecko/Webkit/IE browsers for transform and border-radius. Generally, KUTE.js is built around most used properties, so I highly recommend checking the can I use website for a very detailed properties support list on many browsers and versions. For instance, some legacy browsers may support 2D transforms or 3D transforms so make sure you know what browsers support and how to target them before you get to work with a complete browser supported animation setup.

-

I've put a lot of work in making KUTE.js work with all Internet Explorer versions starting with IE8 and it really works with the help of polyfills and the appropriate code to detect them. All you need to do is to let the browser breathe, espectially IE8 needs to have resize handlers as minimal as possible. On the other side, IE9 really shines with 2D transforms animation, something that's impossible with CSS transition.

-

Speaking of polyfills, KUTE.js no longer requires window.requestAnimationFrame() for the main thread, but it does require the window.performance.now() for checking the current time, .indexOf() for array/string checks, window.getComputedStyle() for the .to() method and .addEventListener() for scroll animation. Unlike other developers I didn't include these polyfills in the code to keep it clean, so that YOU decide whether your project need them or not. Also know that when using the recommended polyfill service some browser detection will not work because they fill the gap and your code won't work as expected. For instance this would check for IE8 browser var isIE = document.all && !document.addEventListener; but the polyfill covers .addEventListener() so you will never succeed. This very demo is a great solution for targeting Microsoft's legacy browsers.

-

As of Safari, we did some tests there too, KUTE.js does it really well.

-
- -
-

Methods, Tools and Options

-

Building Tween Objects

-

KUTE.js allows you to create tween objects with the help of .to() and .fromTo() methods for a single element, with distinctive functionalities, and the other .allTo() and .allFromTo() that use the first two for collections of elements.

- -

KUTE.to('selector', toValues, options) method is super simple and straightforward and requires a polyfill for window.getComputedStyle() Javascript method on IE8 and more other legacy browsers in order to read the current property value. If no value is set in the stylesheets or inline style, a property specific value will be used. It also computes the value on animation start, delaying the actual animation and potentially creating sync issues on large amounts of elements, but it has the great ability to stack transform properties as they come in chained tweens. However fixing the sync issues is not that hard, see the example at start() method API.

- -

KUTE.fromTo('selector', fromValues, toValues, options) is the other method that's most powerful in terms of performance, flexibility and control on the animation. As an example, while the first method may not process properties' measurement units properly, this method will never fail in that regard, because you can set for both starting values and end values the exact values with the right unit you need.

- -

It doesn't stack transform properties for chained tweens but you can set all properties to be used in all tweens if you want (end values from previous tween become start values for the next AND unchanged start values become end values), and make sure nothing is left unchecked, to avoid animation glitches. Still, this method is the fastest and bestest for super performance and super control.

- -

KUTE.allTo('selector', toValues, options) and KUTE.allFromTo('selector', fromValues, toValues, options) inherit all functionality from the .to() and .fromTo() method respectively, but they apply to collections of elements. Unlike the first two methods that create single element tween objects, these two create collections of tween objects. Be sure to check the API documentation on all the methods.

- -

Tween Control

-

Unlike previous versions where animations started right away, starting with version 0.9.5 KUTE.js gives you great animation control methods such as: .start(), .stop(), .pause() and .resume(). These public methods work either when animation is not running, running or is paused. You need to see the documentation to learn how these work.

- -

Tween Options

-

Aside from the usual options such as duration, delay, easing, repeat or yoyo, it also comes with specific tween options for transform. For instance 3D rotations require a perspective or a perspective-origin, right? Well, make sure to check that out.

- -

Callback System

-

Another important KUTE.js feature is the solid callback system. This allows you to schedule functions to run on animation start, on each frame, on pause / resume, on stop and on complete. The functions bound at start or resume will delay the animation, while the functions running on each frame can potentially influence performance on large amounts of elements so you must use them wisely.

- -

Addons

-

KUTE.js sports some fine tuned addons: jQuery Plugin, SVG Plugin, Text Plugin, Attributes Plugin, CSS Plugin, cubic bezier easing functions and also physics based easing functions. It also features an extensive guide on how to extend, but I'm open for more features in the future.

- -

Check the documentation on these methods and the examples page for more.

-
- -
-

Developer Friendly

-

You can develop with KUTE.js for free thanks to the MIT License terms. The terms in short allow you to use the script for free in both personal and commercial application as long as you give proper credits to the original author. Also a link back would be appreciated.

-

Also KUTE.js is super documented, all features and options are showcased with detailed examples so you can get your hands really dirty.

- - -
- - - - -
- - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + KUTE.js Features | Javascript Animation Engine + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+

Features Overview

+

Badass Performance

+

KUTE.js was developed with best practices in mind for fastest code execution and memory efficiency, but performance varies from case to case, as well as for all the other Javascript based animation engines. + As a quick note on how it works, well for the most part values are cached for the entire duration of the animation so that the repetitive tasks run smoothly, uninterruptible and avoid layout thrashing. We all + know the more properties used or the more elements to animate at the same time, the more power is required.

+ +

Of course some would argue on many aspects, but we all trade something for the sake of something else, such as convenience and/or flexibility or fork a project that's already great to make it.. better. + For the sake of performance or simply willing to provide a feature, some trade/neglect other elements such as syncronisation (check this video), code simplicity + (lots of CSS for a custom animation) and more other.

+

To learn more about how performance can vary from case to case, check out this section, it's very informative.

+
+ +
+

Extensible Prototype

+

KUTE.js already packs quite alot of features, and that is thanks to its flexible nature that allows you to easily extend to your heart's desire. Whether you like to extend with CSS properties, easing functions, HTML presentation attributes + or anything that Javascript can touch, even if it's not possible with CSS transitions or other Javascript libraries, KUTE.js makes it super easy.

+

For instance if you want to be able to animate the filter property, you only need three functions: one for preparing the property values needed for tween object build-up, a second function to read current value and the last one + for the DOM update callback, everything else is nicely taken care of. KUTE.js also provides very useful utilities for processing strings, HEX/RGBA colors and other tools you can use for your own plugin's processing.

+

You may want to head over to the extend page for an indepth guide on how to write your own plugin/extension.

+
+ +
+

Auto Browser Prefix

+

KUTE.js uses a simple function to determine the vendor prefix and checks if the prefix is required. In any case it caches the prefixed/unprefixed property name in a variable to make it available when needed. This applies to the following CSS3 + properties: transform, perspective, perspective-origin, border-radius and the requestAnimationFrame Javascript method.

+

We aren't only targeting properly browsers for CSS3 styling, but also increase performance because we don't need to update the styling on every frame for all browsers (and their versions) at once, + just the right and only one; less string concatenation = more performance. This asumes you are NOT styling the above CSS3 properties using your stylesheets to avoid glitches with legacy browsers.

+

This feature is useful mostly for Safari, older Firefox and Opera versions and Internet Explorer 9.

+
+ +
+

Browser Compatibility

+

KUTE.js covers all modern browsers but also provides fallback options for legacy browsers. The prefix free feature mentioned above is one way to enable smooth Javascript based animations on older versions + Gecko/Webkit/IE browsers for transform and border-radius. Generally, KUTE.js is built around most used properties, so I highly recommend checking the can I use website for a very detailed properties support list on many browsers and versions. For instance, some legacy browsers may support 2D transforms or 3D transforms so make sure you know what browsers support and how to target them before you get to work with a complete browser supported animation setup.

+

I've put a lot of work in making KUTE.js work with all Internet Explorer versions starting with IE8 and it really works with the help of polyfills and the appropriate code to detect them. All you need to do is to let the browser breathe, espectially IE8 needs to have resize handlers as minimal as possible. On the other side, IE9 really shines with 2D transforms animation, something + that's impossible with CSS transition.

+

Speaking of polyfills, KUTE.js no longer requires window.requestAnimationFrame() for the main thread, but it does require the window.performance.now() for checking the current time, .indexOf() for array/string + checks, window.getComputedStyle() for the .to() method and .addEventListener() for scroll animation. Unlike other developers I didn't include these polyfills in the code to keep it clean, so that + YOU decide whether your project need them or not. Also know that when using the recommended polyfill service some browser detection will not work because they fill the + gap and your code won't work as expected. For instance this would check for IE8 browser var isIE = document.all && !document.addEventListener; but the polyfill covers .addEventListener() so you will never succeed. + This very demo is a great solution for targeting Microsoft's legacy browsers.

+

As of Safari, we did some tests there too, KUTE.js does it really well.

+
+ +
+

Methods, Tools and Options

+

Building Tween Objects

+

KUTE.js allows you to create tween objects with the help of .to() and .fromTo() methods for a single element, with distinctive functionalities, and the other .allTo() and .allFromTo() that + use the first two for collections of elements.

+ +

KUTE.to('selector', toValues, options) method is super simple and straightforward and requires a polyfill for window.getComputedStyle() Javascript method on IE8 and more other legacy browsers in order to read the current + property value. If no value is set in the stylesheets or inline style, a property specific value will be used. It also computes the value on animation start, delaying the actual animation and potentially creating sync issues on large amounts + of elements, but it has the great ability to stack transform properties as they come in chained tweens. However fixing the sync issues is not that hard, see the example at start() method API.

+ +

KUTE.fromTo('selector', fromValues, toValues, options) is the other method that's most powerful in terms of performance, flexibility and control on the animation. As an example, while the first method may not process properties' + measurement units properly, this method will never fail in that regard, because you can set for both starting values and end values the exact values with the right unit you need.

+ +

It doesn't stack transform properties for chained tweens but you can set all properties to be used in all tweens if you want (end values from previous tween become start values for the next AND unchanged start values become end + values), and make sure nothing is left unchecked, to avoid animation glitches. Still, this method is the fastest and bestest for super performance and super control.

+ +

KUTE.allTo('selector', toValues, options) and KUTE.allFromTo('selector', fromValues, toValues, options) inherit all functionality from the .to() and .fromTo() method respectively, but they apply + to collections of elements. Unlike the first two methods that create single element tween objects, these two create collections of tween objects. Be sure to check the API documentation on all the methods.

+ +

Tween Control

+

Unlike previous versions where animations started right away, starting with version 0.9.5 KUTE.js gives you great animation control methods such as: .start(), .stop(), .pause() and .resume(). + These public methods work either when animation is not running, running or is paused. You need to see the documentation to learn how these work.

+ +

Tween Options

+

Aside from the usual options such as duration, delay, easing, repeat or yoyo, it also comes with specific tween options for transform. For instance 3D rotations require a perspective or a perspective-origin, + right? Well, make sure to check that out.

+ +

Callback System

+

Another important KUTE.js feature is the solid callback system. This allows you to schedule functions to run on animation start, on each frame, on pause / resume, on stop and on complete. The functions bound at start or resume will delay the + animation, while the functions running on each frame can potentially influence performance on large amounts of elements so you must use them wisely.

+ +

Addons

+

KUTE.js sports some fine tuned addons: jQuery Plugin, SVG Plugin, Text Plugin, Attributes Plugin, CSS Plugin, cubic bezier easing functions and also + physics based easing functions. It also features an extensive guide on how to extend, but I'm open for more features in the future.

+ +

Check the documentation on these methods and the examples page for more.

+
+ +
+

Developer Friendly

+

You can develop with KUTE.js for free thanks to the MIT License terms. The terms in short allow you to use the script + for free in both personal and commercial application as long as you give proper credits to the original author. Also a link back would be appreciated.

+

Also KUTE.js is super documented, all features and options are showcased with detailed examples so you can get your hands really dirty.

+ + +
+ + + + +
+ + + + + + + + + + + + + + + + diff --git a/demo/index.html b/demo/index.html index e41ab32..32058a6 100644 --- a/demo/index.html +++ b/demo/index.html @@ -1,218 +1,231 @@ - - - - - - - - - - - - - - - - - KUTE.js | Javascript Animation Engine - - - - - - - - - - - - - - - - - - - -
- -
- - - - -
-
-
-
-

-

-

- Download - Github - CDN 1 - CDN 2 - Replay -

-
-
-
-
-
-
-
-
- -
-
-
- -
-
-
- -
-
- -
-
-
- -
-
-

At A Glance

-
-
-

Badass Performance

-

KUTE.js is crazy fast with it's outstanding performance and super fast code execution, it's also memory efficient. I made a cool demo to showcase how KUTE.js really scales on performance.

-
-
-

Prefix Free

-

KUTE.js can detect if the user's browser requires prefix and uses it accordingly mostly for transform, and even allows you to use the utilities yourself in your apps or your own plugins.

-
-
-
-
-

All Browsers Compatible

-

KUTE.js covers all modern browsers with fallback options for legacy browsers. When using polyfills and the right browser detection you can manage all kinds of fallback animations for legacy browsers.

-
-
-

Powerful Methods

-

KUTE.js allows you to create tweens and chainable tweens, gives you tween control methods (start/stop/pause/resume) and comes with full spectrum tween options.

-
-
-
-
-

Packed With Tools

-

KUTE.js comes with a CSS Plugin, a SVG Plugin, an ATTR Plugin, a Text Plugin and a jQuery plugin, easing functions, color convertors, utility functions, and you can even extend it yourself.

-
-
-

Plenty Of Properties

-

KUTE.js covers all animation needs such as SVG morph & transform and other specific CSS properties, then CSS3 transform, scroll, border-radius, and almost the full box model or text properties.

-
-
-
-
-

MIT License

-

You can develop with KUTE.js for free thanks to the MIT License terms.

-
-
-

Top Notch Documentation

-

All examples, code, tips & tricks are very well documented.

-
-
-
-
- -
-

Getting Started

-
-
- -

Examples

-

See KUTE.js in action with all it's functions, options and features.

-
-
- -

Documentation

-

The API documentation is here for you to get you started.

-
- -
- -

Performance

-

Head over to the performance test page right away.

-
-
- - - -
- - - - -
- - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + KUTE.js | Javascript Animation Engine + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + +
+
+
+
+

+

+

+ Download + Github + CDN 1 + CDN 2 + Replay +

+
+
+
+
+
+
+
+
+ +
+
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+

At A Glance

+
+
+

Badass Performance

+

KUTE.js is crazy fast with it's outstanding performance and super fast code execution, it's also memory efficient. I made a cool demo to showcase how KUTE.js + really scales on performance.

+
+
+

Prefix Free

+

KUTE.js can detect if the user's browser requires prefix and uses it accordingly mostly for transform, and even allows you to use the utilities yourself in your apps or your own plugins.

+
+
+
+
+

All Browsers Compatible

+

KUTE.js covers all modern browsers with fallback options for legacy browsers. When using polyfills and the right browser detection you can manage all kinds of fallback animations for legacy browsers.

+
+
+

Powerful Methods

+

KUTE.js allows you to create tweens and chainable tweens, gives you tween control methods (start/stop/pause/resume) and comes with full spectrum tween options.

+
+
+
+
+

Packed With Tools

+

KUTE.js comes with a CSS Plugin, a SVG Plugin, + an ATTR Plugin, a Text Plugin and a jQuery plugin, easing functions, + color convertors, utility functions, and you can even extend it yourself.

+
+
+

Plenty Of Properties

+

KUTE.js covers all animation needs such as SVG morph & transform and other specific CSS properties, then CSS3 transform, scroll, border-radius, and almost + the full box model or text properties.

+
+
+
+
+

MIT License

+

You can develop with KUTE.js for free thanks to the MIT License terms.

+
+
+

Top Notch Documentation

+

All examples, code, tips & tricks are very well documented.

+
+
+
+
+ +
+

Getting Started

+
+
+ +

Examples

+

See KUTE.js in action with all it's functions, options and features.

+
+
+ +

Documentation

+

The API documentation is here for you to get you started.

+
+ +
+ +

Performance

+

Head over to the performance test page right away.

+
+
+ + + +
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/demo/options.html b/demo/options.html index fbd1886..cc62462 100644 --- a/demo/options.html +++ b/demo/options.html @@ -3,7 +3,9 @@ - + + + @@ -12,138 +14,148 @@ - + + KUTE.js Tween Options | Javascript Animation Engine - + - + - + - - - + + + - - - - - + + + + + -
- - + -
-

Tween Options

-

Any animation can be customized in many ways for duration, progress / easing, delay and even for specific plugins. Some of these options have a default value and starting with KUTE.js version 1.6.1 you can override these default values, as we'll see later on this page.

+
+

Tween Options

+

Any animation can be customized in many ways for duration, progress / easing, delay and even for specific plugins. Some of these options have a default value and starting with KUTE.js version 1.6.1 you can override these default values, as + we'll see later on this page.

-

Common Options

-

These options affect all types of tweens, no matter the properties used or context.

-
    -
  • duration: 500 option allows you to set the animation duration in miliseconds. The default value is 700.
  • -
  • repeat: 20 option allows you to run the animation of given tween multiple times. The default value is 0.
  • -
  • delay: 500 option allows you to delay the tween animation for a certain number of miliseconds. The default value is 0.
  • -
  • offset: 200 option is only for .allTo() and .allFromTo() methods. This allows you to set a base delay in miliseconds that increases with each element in the collection. This has no effect on other methods and the default value is 0.
  • -
  • repeatDelay: 500 option allows you to set a number of miliseconds delay between repeatable animations. If repeat option is set to 0, will produce no effect. The default value is 0.
  • -
  • yoyo: true/false option makes use of the internal reverse functionality to also animate from end to start for a given tween. This option requires that you use the repeat option with at least value 1. The default value is false.
  • -
  • easing: 'easingCubicInOut' option allows you to use a custom easing function for your animation. For more info on the easing functions, you need to see the example pages. The default value is linear.
  • -
+

Common Options

+

These options affect all types of tweens, no matter the properties used or context.

+
    +
  • duration: 500 option allows you to set the animation duration in miliseconds. The default value is 700.
  • +
  • repeat: 20 option allows you to run the animation of given tween multiple times. The default value is 0.
  • +
  • delay: 500 option allows you to delay the tween animation for a certain number of miliseconds. The default value is 0.
  • +
  • offset: 200 option is only for .allTo() and .allFromTo() methods. This allows you to set a base delay in miliseconds that increases with each element in the collection. This has no effect on other methods + and the default value is 0.
  • +
  • repeatDelay: 500 option allows you to set a number of miliseconds delay between repeatable animations. If repeat option is set to 0, will produce no effect. The default value is 0.
  • +
  • yoyo: true/false option makes use of the internal reverse functionality to also animate from end to start for a given tween. This option requires that you use the repeat option with at least value + 1. The default value is false.
  • +
  • easing: 'easingCubicInOut' option allows you to use a custom easing function for your animation. For more info on the easing functions, you need to see the example pages. The default value is linear.
  • +
-

Transform Options

-

These options only affect animation involving any 3D property from CSS3 transform and have no effect on other CSS properties. While you can set perspective or perspective origin via CSS, these options are here to help, especially with full browser support and preffix free handling.

-
    -
  • perspective: 500 option allows you to set a 3D transformation perspective for a given HTML element. No default value.
  • -
  • perspectiveOrigin: "50% 50%" option allows you to set a perspectiveOrigin for a given HTML element. This option has no default value and only accepts valid CSS values according to it's specs.
  • -
  • parentPerspective: 500 option allows you to set a 3D perspective for the parent of the HTML element subject to the transform animation. No default value.
  • -
  • parentPerspectiveOrigin: "50% 50%" option allows you to set a perspectiveOrigin for the parent of the HTML element subject to the transform animation. Also like the above similar options, this options only accepts valid CSS values and has no default value.
  • -
  • transformOrigin: "50% 50%" option allows you to set a transformOrigin for the HTML/SVG element subject for the transform animation. Starting KUTE.js 1.6.0 this option also aplies to SVG transforms featured with the SVG Plugin. This options only accepts valid CSS values for CSS3 transforms, but keep in mind that for both CSS3 transform and SVG transform attribute KUTE.js will always think of "50% 50%" as the default value, even if most browser's default value for SVG transform origin is "0px 0px 0px" and the reason is simply consistency all round. When applied to a svgTransform property, it can also accept array values: transformOrigin: [250,250]. There is no default value but the SVG Plugin will always use 50% 50% for your transform tweens.
  • -
+

Transform Options

+

These options only affect animation involving any 3D property from CSS3 transform and have no effect on other CSS properties. While you can set perspective or perspective origin via CSS, these options + are here to help, especially with full browser support and preffix free handling.

+
    +
  • perspective: 500 option allows you to set a 3D transformation perspective for a given HTML element. No default value.
  • +
  • perspectiveOrigin: "50% 50%" option allows you to set a perspectiveOrigin for a given HTML element. This option has no default value and only accepts valid CSS values according to it's specs.
  • +
  • parentPerspective: 500 option allows you to set a 3D perspective for the parent of the HTML element subject to the transform animation. No default value.
  • +
  • parentPerspectiveOrigin: "50% 50%" option allows you to set a perspectiveOrigin for the parent of the HTML element subject to the transform animation. Also like the above similar options, this options only accepts + valid CSS values and has no default value.
  • +
  • transformOrigin: "50% 50%" option allows you to set a transformOrigin for the HTML/SVG element subject for the transform animation. Starting KUTE.js 1.6.0 this option also aplies to SVG transforms featured with + the SVG Plugin. This options only accepts valid CSS values for CSS3 transforms, but keep in mind that for both CSS3 transform and SVG transform attribute KUTE.js will always think of "50% 50%" as the default value, even if most browser's + default value for SVG transform origin is "0px 0px 0px" and the reason is simply consistency all round. When applied to a svgTransform property, it can also accept array values: transformOrigin: [250,250]. + There is no default value but the SVG Plugin will always use 50% 50% for your transform tweens.
  • +
-

SVG Plugin Options

-

The following options only affect animation of the path tween property, to customize the SVG morph animation. See SVG Plugin page.

-
    -
  • morphPrecision: Number option allows you to set the sampling size of the morph. The lesser value the better visual but the more power required.
  • -
  • morphIndex: Number option allows you to rotate the second/end path in a way that the points travel the least possible distance during morph, and as an effect the morph animation feel more "natural".
  • -
  • reverseFirstPath: true when is true this option allows you to reverse the draw direction of the FIRST shape.
  • -
  • reverseSecondPath: true when is true this option allows you to reverse the draw direction of the SECOND shape.
  • -
+

SVG Plugin Options

+

The following options only affect animation of the path tween property, to customize the SVG morph animation. See SVG Plugin page.

+
    +
  • morphPrecision: Number option allows you to set the sampling size of the morph. The lesser value the better visual but the more power required.
  • +
  • morphIndex: Number option allows you to rotate the second/end path in a way that the points travel the least possible distance during morph, and as an effect the morph animation feel more "natural".
  • +
  • reverseFirstPath: true when is true this option allows you to reverse the draw direction of the FIRST shape.
  • +
  • reverseSecondPath: true when is true this option allows you to reverse the draw direction of the SECOND shape.
  • +
-

Text Plugin Options

-

The only option for the plugin is the textChars option for the text property and allows you to set the characters set for the scrambling character during the animation. See Text Plugin page for more instructions and demo.

- -

Callback Options

-

These options also affect all types of tweens, and are bound by the tween control options and the internal update functions.

-
    -
  • start: function option allows you to set a function to run once tween animation starts.
  • -
  • update: function option allows you to set a function to run on every frame.
  • -
  • pause: function option allows you to set a function to run when animation is paused.
  • -
  • resume: function option allows you to set a function to run when animation is resumed.
  • -
  • stop: function option allows you to set a function to run when animation is stopped.
  • -
  • complete: function option allows you to set a function to run when animation is finished.
  • -
- -

A quick example would look like this:

-
//define a function
+            

Text Plugin Options

+

The only option for the plugin is the textChars option for the text property and allows you to set the characters set for the scrambling character during the animation. See Text Plugin page for more instructions and demo.

+ +

Callback Options

+

These options also affect all types of tweens, and are bound by the tween control options and the internal update functions.

+
    +
  • start: function option allows you to set a function to run once tween animation starts.
  • +
  • update: function option allows you to set a function to run on every frame.
  • +
  • pause: function option allows you to set a function to run when animation is paused.
  • +
  • resume: function option allows you to set a function to run when animation is resumed.
  • +
  • stop: function option allows you to set a function to run when animation is stopped.
  • +
  • complete: function option allows you to set a function to run when animation is finished.
  • +
+ +

A quick example would look like this:

+
//define a function
 var callback = function(){
-	//do some foo
+  //do some foo
 }
 
 //create object and start animating already
 KUTE.fromTo(div,{left:150},{left:0},{complete: callback}).start();
-
-

Other Options

-

keepHex: true option allows you to always use HEX color format, even if you have used RGB or RGBA. This option is useful when tweening color properties on legacy browsers, however modern browsers may ignore this option for performance reasons.

+
+

Other Options

+

keepHex: true option allows you to always use HEX color format, even if you have used RGB or RGBA. This option is useful when tweening color properties on legacy browsers, however modern browsers + may ignore this option for performance reasons.

-

Override Default Options' Values

-

Most options have a default value as you can see above, they are globally defined in the KUTE.defaultOptions object like so:

-
// the list of all tween options that can be overrided
+            

Override Default Options' Values

+

Most options have a default value as you can see above, they are globally defined in the KUTE.defaultOptions object like so:

+
// the list of all tween options that can be overrided
 KUTE.defaultOptions = {
     duration: 700,
     delay: 0,
@@ -158,47 +170,51 @@ KUTE.defaultOptions = {
 };
 
-

As some user suggested, he would need a way to override the default duration value, here's how to:

- -
// sets the new global duration tween option default value 
+            

As some user suggested, he would need a way to override the default duration value, here's how to:

+ +
// sets the new global duration tween option default value
 KUTE.defaultOptions.duration = 1000;
-
-

Also make sure to define the new option global default values before you define your tween objects.

-
+ +

Also make sure to define the new option global default values before you define your tween objects.

+
-
+
- - -
- - - + -
- + + + + + + + - - + - - + + - + - - + + + + + diff --git a/demo/performance.html b/demo/performance.html index 320a185..3eb0b42 100644 --- a/demo/performance.html +++ b/demo/performance.html @@ -8,125 +8,173 @@ - + + KUTE.js | Performance Testing Page - + - + - -
-

Back to KUTE.js

-

Engine

+ +
+

Back to KUTE.js

+

Engine

- - -

Property

+ +

Property

- - - -

Repeat

+ + +

Repeat

- - - -

How many elements to animate:

+ + +

How many elements to animate:

- + - +
- +
- +
- - - -

These tests are only for modern browsers. In Webkit browsers like Google Chrome and Opera you can enable the FPS metter in developer tools, here's how.

-

Please know that a local copy of this page will outperform the live site demo on Google Chrome, the reason is unknown.

- -
+ + +

These tests are only for modern browsers. In Webkit browsers like Google Chrome and Opera you can enable the FPS metter in developer tools, here's how.

+

Please know that a local copy of this page will outperform the live site demo on Google Chrome, the reason is unknown.

+ -
+
- +
- - - + + - - + + - - - - - - + + + + + + + diff --git a/demo/properties.html b/demo/properties.html index ba61d2b..3993401 100644 --- a/demo/properties.html +++ b/demo/properties.html @@ -3,7 +3,9 @@ - + + + @@ -12,227 +14,271 @@ - + + KUTE.js Supported Properties | Javascript Animation Engine - + - + - - + + - + - - - + + + + -
- -
- - + +
+ +
+ + + +
- -
-

Supported Properties

-

KUTE.js covers all animation needs by itself for transform properties, scroll for window or a given element, colors. Note: not all browsers support 2D transforms or 3D transforms. With the help of some plugins it also covers SVG specific properties, presentation attributes, or other CSS properties like border-radius, clip, backgroundPosition and more box model properties.

-

Starting with KUTE.js version 1.5.0 the supported properties are split among some plugins to have a lighter core engine that gives more power to the developer. Due to it's modular coding, KUTE.js makes it easy to add support for additional properties, so check out the guide on how to extend.

-

All common measurement units are supported: px and % for translations and box-model properties, or deg and rad for rotations and skews, while clip only supports px. Other properties such as opacity, scale or scroll are unitless, and background-position always uses % as measurement unit. As for the text properties you can use px, em, rem, vh and vw. Be sure to check what your browsers support in terms of measurement unit.

- -

Opacity

-

In most cases, the best animation possible is the opacity, for performance, aesthetics and maybe more other reasons such as avoiding unwanted layout changes. KUTE.js also covers IE8 here with the help of proprietary synthax filter: alpha(opacity=0). Also, opacity can be used for instance on legacy browsers that don't support RGBA colors. Eg. opacity:0.5 will make an element semitransparent.

- -

2D Transform Properties

-

The core engine supports most 2D transform properties, but the most important part is that starting with KUTE.js v1.6.0 the values used for animation are always converted from percentage based translation to pixels and radians based angles to degrees, to help improve memory efficiency.

-
    -
  • translate property can be used for horizontal and / or vertical movement. EG. translate:150 to translate an element 150px to the right or translate:[-150,200] to move the element to the left by 150px and to bottom by 200px. IE9+
  • -
  • rotate property applies rotation to an element on the Z axis or the plain document. Eg. rotate:250 will rotate an element clockwise by 250 degrees. IE9+
  • -
  • skewX property applies a skew transformation on the X axis. Eg. skewX:25 will skew an element by 25 degrees. IE9+
  • -
  • skewY property applies a skew transformation on the Y axis. Eg. skewY:25 will skew an element by 25 degrees. IE9+
  • -
  • scale property applies a single value size transformation. Eg. scale:2 will enlarge an element by a degree of 2. IE9+
  • -
  • matrix, double axis skew and double axis scale properties are not supported.
  • -
- -

3D Transform Properties

-

The core engine supports all 3D transform properties except matrix3d and rotate3d. Just as the above, these properties' values are also converted to traditional pixels and degrees measurements to help improve memory usage.

-
    -
  • translateX property is for horizontal translation. EG. translateX:150 to translate an element 150px to the right. IE10+
  • -
  • translateY property is for vertical translation. EG. translateY:-250 to translate an element 250px towards the top. IE10+
  • -
  • translateZ property is for translation on the Z axis in a given 3D field. EG. translateZ:-250 to translate an element 250px to it's back, making it smaller. Requires a perspective tween option to be used; the smaller perspective value, the deeper translation. IE10+
  • -
  • translate3d property is for movement on all the axis in a given 3D field. EG. translate3d:[-150,200,150] to translate an element 150px to the left, 200px to the bottom and 150px closer to the viewer, making it larger. Also requires using a perspective tween option. IE10+
  • -
  • rotateX property rotates an element on the X axis in a given 3D field. Eg. rotateX:250 will rotate an element clockwise by 250 degrees. Requires perspective. IE10+
  • -
  • rotateY property rotates an element on the Y axis in a given 3D field. Eg. rotateY:-150 will rotate an element counter-clockwise by 150 degrees. Requires perspective. IE10+
  • -
  • rotateZ property rotates an element on the Z axis and is the equivalent of the 2D rotation. Eg. rotateZ:-150 will rotate an element counter-clockwise by 150 degrees. IE10+
  • -
  • matrix3d, rotate3d, and scale3d properties are not supported.
  • -
- -

SVG Transform

-

The SVG Plugin features cross browser 2D transform animations via the svgTransform tween property and the transform presentation attribute, similar in functionality as the Attributes Plugin.

-
    -
  • translate sub-property applies horizontal and / or vertical translation. EG. translate:150 to translate a shape 150px to the right or translate:[-150,200] to move the element to the left by 150px and to bottom by 200px. IE9+
  • -
  • rotate sub-property applies rotation to a shape on the Z axis. Eg. rotate:150 will rotate a shape clockwise by 150 degrees around it's own center or around the transformOrigin: '450 450' set tween option coordinate of the parent element. IE9+
  • -
  • skewX sub-property used to apply a skew transformation on the X axis. Eg. skewX:25 will skew a shape by 25 degrees. IE9+
  • -
  • skewY sub-property used to apply a skew transformation on the Y axis. Eg. skewY:25 will skew a shape by 25 degrees. IE9+
  • -
  • scale sub-property used to apply a single value size transformation. Eg. scale:0.5 will scale a shape to half of it's initial size. IE9+
  • -
  • matrix sub-property is not supported.
  • -
-

As a quick note, the translation is normalized and computed in a way to handle the transformOrigin tween option in all cases, not just for rotations, but also scaling or skews.

- -

SVG Properties

-

The SVG Plugin can animate the d attribute of a given <path> or <glyph> element with the tween property called path. The animation effect is widelly known as morph SVG and implemented in various scripts, but the KUTE.js implementation is similar to the D3.js examples for wider usability and the ability to optimize the visual and performance of the morph, all with the help of special tween options and utilities.

- -

Further more, the SVG Plugin can animate the stroke in a way that you probably know as drawSVG. KUTE.js implements it as draw tween property that deals with the well known CSS properties: strokeDasharray and strokeDashoffset. - -

Box Model Properties

-

The core engine supports width, height, left and top while the CSS Plugin adds support for all other box-model properties.

-
    -
  • left, top, right and bottom are position based properties for movement on vertical and / or horizontal axis. These properties require that the element to animate uses position: absolute/relative styling as well as it's parent element requires position:relative. These properties can be used as fallback for browsers with no support for translate properties such as IE8.
  • -
  • width, height, minWidth, minHeight, maxWidth, maxHeight are properties that allow you to animate the size of an element on horizontal and / or vertical axis. These properties can be used on images as fallback for scale on IE8 again, as well as for other purposes.
  • -
  • padding, margin, paddingTop, paddingBottom, paddingLeft, paddingRight, marginTop, marginBottom, marginLeft and marginRight are properties that allow you to animate the spacing of an element inside (via padding) and outside (via margin). Shorthand notations such as margin: "20px 50px" or any other type are not supported.
  • -
  • borderWidth, borderTopWidth, borderRightWidth, borderBottomWidth are borderLeftWidth are properties that allow you to animate the border of an element either on all sides at once or each side separatelly. Shorthand notations are not supported.
  • -
  • outlineWidth property allows you to animate the outline-width of an element.
  • -
-

As a quick side note, starting with KUTE.js v1.6.0 the core engine supported box model properties values are converted from percent based into pixel based values, using the element.offsetWidth as a refference. The idea is the same as presented on the above supported transform properties.

-

Remember: these properties are layout modifiers that may force repaint of the entire DOM, drastically affecting performance on lower end and mobile devices. They also trigger resize event that may cause crashes on old browsers such as IE8 when using handlers bound on resize, so use with caution.

- -

Border Radius

-

The CSS Plugin covers all the radius properties with the exception that shorthand notations are not implemented.

-
    -
  • borderRadius allows you to animate the border-radius on all corners for a given element.
  • -
  • borderTopLeftRadius allows you to animate the border-top-left-radius for a given element.
  • -
  • borderTopRightRadius allows you to animate the border-top-right-radius for a given element.
  • -
  • borderBottomLeftRadius allows you to animate the border-bottom-left-radiusfor a given element.
  • -
  • borderBottomRightRadius allows you to animate the border-bottom-right-radiusfor a given element.
  • -
-

For all radius properties above borderRadius:20 or borderTopLeftRadius:'25%' will do. In the first case px is the default measurement unit used, while in the second we require using % unit which is relative to the element's size.

-

Remember: shorthands for border-radius are not supported. Also KUTE.js does not cover early implementations by Mozilla Firefox (Eg. -moz-border-radius-topleft) as they were deprecated with later versions.

- -

Color Properties

-

The core engine only supports color and backgroundColor, but the CSS Plugin covers all the others. KUTE.js currently supports values such as HEX, RGB and RGBA for all color properties, but IE8 does not support RGBA and always uses RGB when detected, otherwise will produce no effect. There is also a tween option keepHex:true to convert the color format. Eg. color: '#ff0000' or backgroundColor: 'rgb(202,150,20)' or borderColor: 'rgba(250,100,20,0.5)'. The IE9+ browsers should also work with web safe colors, eg. color: 'red'.

-
    -
  • color allows you to animate the color for a given text element.
  • -
  • backgroundColor allows you to animate the background-color for a given element.
  • -
  • outlineColor allows you to animate the outline-color for a given element.
  • -
  • borderColor allows you to animate the border-color on all sides for a given element.
  • -
  • borderTopColor, borderRightColor, borderBottomColor and borderLeftColor properties allow you to animate the color of the border on each side of a given element.
  • -
-

Remember: shorthands for borderColor property are not supported.

- -

Presentation Attributes

-

The Attributes Plugin can animate any numerical presentation attribute such as width, cx or stop-opacity, but the values can be also suffixed: 150px or 50%, and for that you must always provide a string value that include the measurement unit, and that, of course, depends on the attribute. This plugin can be a great addition to the above SVG Plugin for specific gradient attributes or specific geometric shapes' attributes.

-

Starting KUTE.js 1.6.0 the Attributes Plugin can also animate color attributes such as stroke, fill or stop-color, and they are removed from the SVG Plugin, and the reason for that is the new bundle build that incorporates both plugins into an unified file.

-

The synthax is slightly different to make sure we don't mess up with CSS properties that have the same name because the presentation attribute may be a unitless attribute while the CSS property might require a suffix (%,px,etc). For instance KUTE.to('selector', {attr:{width:150}}) is clearly different from KUTE.to('selector', {width:150}) which is the the CSS property with the same name.

-

The plugin handles attribute namespaces properly which means you can use both Javascript notation (like stopColor) and HTML markup notation (like 'stop-color'), see the below example.

-

EG: KUTE.to('selector', {attr:{stroke:'blue'}}) to animate the stroke of an SVG element or KUTE.to('selector', {attr:{'stop-color':'red'}}) to animate the stop color of some SVG gradient.

- -

Typography Properties

-

The CSS Plugin also cover the text properties, and these can be combinated with each other when applied to text elements (paragraphs, headings) as animation fallback for scale on browsers that don't support transform at all. Yes, IE8 and other legacy browsers.

-
    -
  • fontSize allows you to animate the font-size for a given element.
  • -
  • lineHeight allows you to animate the line-height for a given element.
  • -
  • letterSpacing allows you to animate the letter-spacing for a given element.
  • -
  • wordSpacing allows you to animate the word-spacing for a given element.
  • -
-

Remember: these properties are layout modifiers.

- -

Scroll Animation

-

KUTE.js core engine currently supports only vertical scroll for both the window and a given element that's scrollable (when scrollHeight is higher than offsetHeight). EG: scroll: 150 will scroll an element or window to 150px from top to bottom. When animating scroll, KUTE.js will disable all scroll and swipe handlers to prevent animation bubbles as well as scroll bottlenecks, but we'll have a look at that later.

- -

String Properties

-
    -
  • number allows you to tween a number either from 0 or from a current value and updates the innerHTML for a given target. Eg. number:1500
  • -
  • text allows you to write a string one character at a time followed by a scrambling character. Eg. text: 'A demo with <b>substring</b>'.
  • -
-

See Text Plugin for details.

- -

Other Properties

-
    -
  • clip allows you to animate the clip property for a given element. Only rect is supported. Eg. clip:[250,200,300,0]. See spec for details.
  • -
  • backgroundPosition allows you to animate the background-position for a given element that uses a background image. It only uses % as measurement unit. Eg. backgroundPosition:[50,20]
  • -
- -

Legend

-
    -
  • core - the property/properties are supported by core animation engine.
  • -
  • plugin - the property/properties are supported by plugins.
  • -
  • unsupported - the property/properties are NOT supported by core and/or plugins.
  • -
- -

Did We Miss Any Important Property?

-

Make sure you go to the issues tracker and report the missing property ASAP, or you can check the extend guide and learn how to develop a plugin to support a new property yourself.

-
- -
- -
- - - - - - + - - + - + - - + + + + + diff --git a/demo/start.html b/demo/start.html index 3c507e0..afa4321 100644 --- a/demo/start.html +++ b/demo/start.html @@ -3,7 +3,9 @@ - + + + @@ -12,88 +14,89 @@ - + + Getting Started with KUTE.js | Javascript Animation Engine - + - + - + - - - + + + - - - - - + + + + + -
- -
- - +
-
- -

Getting Started

-

Welcome to KUTE.js API documentation, here we're going to talk about how to download, install, use, control and set up cross browser animations, in great detail. KUTE.js can be found on CDN and also npm and Bower repositories with all it's features and tools.

+
-

Bower and NPM

-

You can install KUTE.js package by using either Bower or NPM.

-
$ npm install --save kute.js
+        
+
+        
+ +

Getting Started

+

Welcome to KUTE.js API documentation, here we're going to talk about how to download, install, use, control and set up cross browser animations, in great detail. KUTE.js can be found on CDN and also npm and Bower repositories with all it's features and tools.

+ +

Bower and NPM

+

You can install KUTE.js package by using either Bower or NPM.

+
$ npm install --save kute.js
 # Or
 $ bower install --save kute.js
 
-

Require and CommonJS

-
// CommonJS style
+            

Require and CommonJS

+
// CommonJS style
 var kute = require("kute.js"); //grab the core
 require("kute.js/kute-svg"); // Add SVG Plugin
 require("kute.js/kute-css"); // Add CSS Plugin
@@ -101,7 +104,7 @@ require("kute.js/kute-attr"); // Add Attributes Plugin
 require("kute.js/kute-text"); // Add Text Plugin
 
-
// AMD style
+            
// AMD style
 define([
     "kute.js",
     "kute.js/kute-jquery.js", // optional for jQuery apps
@@ -113,65 +116,72 @@ define([
     // ...
 });
 
- -

Websites

-

In your website add the following code, the best would be to put it at the end of your body tag:

-
<script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute.min.js"></script> <!-- core KUTE.js -->
-

An alternate CDN link here:

-
<script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute.min.js"></script> <!-- core KUTE.js -->
-

The CDN repositories receive latest updates here and right here. You might also want to include the tools that you need for your project:

-
<script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-jquery.min.js"></script> <!-- jQuery Plugin -->
+            

Websites

+

In your website add the following code, the best would be to put it at the end of your body tag:

+
<script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute.min.js"></script> <!-- core KUTE.js -->
+

An alternate CDN link here:

+
<script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute.min.js"></script> <!-- core KUTE.js -->
+ +

The CDN repositories receive latest updates here and right here. You might also want to include the tools that + you need for your project:

+
<script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-jquery.min.js"></script> <!-- jQuery Plugin -->
 <script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-css.min.js"></script> <!-- CSS Plugin -->
 <script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-svg.min.js"></script> <!-- SVG Plugin -->
 <script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-text.min.js"></script> <!-- Text Plugin -->
 <script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-attr.min.js"></script> <!-- Attributes Plugin -->
 
-

Alternate CDN links:

-
<script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute-jquery.min.js"></script> <!-- jQuery Plugin -->
+            

Alternate CDN links:

+
<script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute-jquery.min.js"></script> <!-- jQuery Plugin -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute-css.min.js"></script> <!-- CSS Plugin -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute-svg.min.js"></script> <!-- SVG Plugin -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute-text.min.js"></script> <!-- Text Plugin -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute-attr.min.js"></script> <!-- Attributes Plugin -->
 
-

Your awesome animation coding would follow after these script links.

- -

Targeting Legacy Browsers

-

You need to know when users' browser is a legacy one in order to use KUTE.js only for what browsers actually support. A quick note here: IE8 doesn't support any transform property or RGBA colors while IE9 can only do 2D transformations. Check the 2D transforms and the 3D transforms browser support list for more information.

-

Don't use Modernizr, the best thing you can actually do is to use the Microsoft's synthax for it's own legacy browsers, and here is the full refference on that. For other legacy browsers there is a ton of ways to target them, quite efficiently I would say: there you go.

+

Your awesome animation coding would follow after these script links.

+ +

Targeting Legacy Browsers

+

You need to know when users' browser is a legacy one in order to use KUTE.js only for what browsers actually support. A quick note here: IE8 doesn't support any transform property or RGBA colors while IE9 can only + do 2D transformations. Check the 2D transforms and the 3D transforms browser support list for more + information.

+

Don't use Modernizr, the best thing you can actually do is to use the Microsoft's synthax for it's own legacy browsers, and here is the full refference on that. For other legacy browsers there is a ton of ways to target them, quite efficiently I would say: there you go.

- - -
- - - + -
- +
+ + + + +
+ - - + - - + + - + - - + + + + + diff --git a/demo/svg.html b/demo/svg.html index f6ce659..2ff8d92 100644 --- a/demo/svg.html +++ b/demo/svg.html @@ -3,7 +3,9 @@ - + + + @@ -12,238 +14,258 @@ - + + KUTE.js SVG Plugin | Javascript Animation Engine - + - + - + - - - - + + + + - - - + + + + -
- -
- - +
-
-

SVG Plugin

-

The SVG Plugin for KUTE.js extends the core engine and enables animation for various SVG specific CSS properties, SVG morphing of path shapes and SVG transforms. We'll dig into this in great detail as well as provide valuable tips on how to configure your animation for best performance and visual aesthetics. The SVG Plugin is very light, maybe one of the lightest out there, still, you will find it to be very powerful and flexible.

-

Keep in mind that older browsers like Internet Explorer 8 and below as well as stock browser from Android 4.3 and below do not support inline SVG so make sure to fiter out your SVG tweens.

-

SVG Morphing

-

One of the most important parts of the plugin is the SVG morphing capability. It only applies to inline <path> and <glyph> SVG elements, with closed shapes (their d attribute ends with z). On initialization or animation start, depending on the chosen KUTE.js method, it will sample a number of points along the two paths based on a default / given sample size and will create two arrays with these points, the arrays that we need for interpolation. Further more, with a set of options we can then rearrange / reverse these arrays to optimize and / or maximize the visual effect of the morph:

-
    -
  • morphPrecision: Number option allows you to set the sampling size of the morph. The lesser value the better visual but the more power consumption and less performance. The default value is 15 but the D3.js example uses 4.
  • -
  • morphIndex: Number option allows you to rotate the second/end path in a way that the points travel the least possible distance during morph, and as an effect the morph animation feel more "natural". By default, this option is not set.
  • -
  • reverseFirstPath: true when is true this option allows you to reverse the draw direction of the FIRST shape. By default this option is false.
  • -
  • reverseSecondPath: true when is true this option allows you to reverse the draw direction of the SECOND shape. By default this option is also false.
  • -
-

Basic Example

-

In the first morph example we are going to go through some basic steps on how to setup and how to improve the morph animation. Our demo is a morph from a rectangle into a star, so first let's create an SVG element with two paths, first is going to be visible, filled with color, while second is going to be hidden. The first path is the start shape and the second is the end shape, you guessed it, and we can also add some ID to the paths so we can easily target them with our code.

-
<svg id="morph-example" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600">
+    
+ + + +
+

SVG Plugin

+

The SVG Plugin for KUTE.js extends the core engine and enables animation for various SVG specific CSS properties, SVG morphing of path shapes and SVG transforms. We'll dig into this in great detail as well as provide valuable tips on how to + configure your animation for best performance and visual aesthetics. The SVG Plugin is very light, maybe one of the lightest out there, still, you will find it to be very powerful and flexible.

+

Keep in mind that older browsers like Internet Explorer 8 and below as well as stock browser from Android 4.3 and below do not support inline SVG so make sure to fiter out your SVG + tweens.

+

SVG Morphing

+

One of the most important parts of the plugin is the SVG morphing capability. It only applies to inline <path> and <glyph> SVG elements, with closed shapes (their d attribute ends with z). + On initialization or animation start, depending on the chosen KUTE.js method, it will sample a number of points along the two paths based on a default / + given sample size and will create two arrays with these points, the arrays that we need for interpolation. Further more, with a set of options we can then rearrange / reverse these arrays to optimize and / or maximize the visual effect + of the morph:

+
    +
  • morphPrecision: Number option allows you to set the sampling size of the morph. The lesser value the better visual but the more power consumption and less performance. The default value is 15 but the + D3.js example uses 4.
  • +
  • morphIndex: Number option allows you to rotate the second/end path in a way that the points travel the least possible distance during morph, and as an effect the morph animation feel more "natural". By default, this option is + not set.
  • +
  • reverseFirstPath: true when is true this option allows you to reverse the draw direction of the FIRST shape. By default this option is false.
  • +
  • reverseSecondPath: true when is true this option allows you to reverse the draw direction of the SECOND shape. By default this option is also false.
  • +
+

Basic Example

+

In the first morph example we are going to go through some basic steps on how to setup and how to improve the morph animation. Our demo is a morph from a rectangle into a star, so first let's create an SVG element with two paths, first is + going to be visible, filled with color, while second is going to be hidden. The first path is the start shape and the second is the end shape, you guessed it, and we can also add some ID to the paths so we can easily target them with our + code.

+
<svg id="morph-example" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600">
     <path id="rectangle" class="bg-lime" d="M38.01,5.653h526.531c17.905,0,32.422,14.516,32.422,32.422v526.531 c0,17.905-14.517,32.422-32.422,32.422H38.01c-17.906,0-32.422-14.517-32.422-32.422V38.075C5.588,20.169,20.104,5.653,38.01,5.653z"/>
     <path id="star" style="visibility:hidden" d="M301.113,12.011l99.25,179.996l201.864,38.778L461.706,380.808 l25.508,203.958l-186.101-87.287L115.01,584.766l25.507-203.958L0,230.785l201.86-38.778L301.113,12.011"/>
 </svg>
 
-

Now we can apply both .to() and fromTo() methods:

-
// the fromTo() method
+            

Now we can apply both .to() and fromTo() methods:

+
// the fromTo() method
 var tween = KUTE.fromTo('#rectangle', {path: '#rectangle' }, { path: '#star' }).start();
 
 // OR
 
 // the to() method will take the path's d attribute value and use it as start value
-var tween = KUTE.to('#rectangle', { path: '#star' }).start(); 
+var tween = KUTE.to('#rectangle', { path: '#star' }).start();
 
 // OR
 
 // simply pass in a valid path string without the need to have two paths in your SVG
-var tween = KUTE.to('#rectangle', { path: 'M301.113,12.011l99.25,179.996l201.864,38.778L461.706,380.808l25.508,203.958l-186.101-87.287L115.01,584.766l25.507-203.958L0,230.785l201.86-38.778L301.113,12.011' }).start(); 
-
+var tween = KUTE.to('#rectangle', { path: 'M301.113,12.011l99.25,179.996l201.864,38.778L461.706,380.808l25.508,203.958l-186.101-87.287L115.01,584.766l25.507-203.958L0,230.785l201.86-38.778L301.113,12.011' }).start(); +
-

For all the above tween objects the animation should look like this:

+

For all the above tween objects the animation should look like this:

-
- +
+ -
- Start -
-
- -

As you can see, the animation could need some fine tunning. Let's go ahead and play with the new utility, it's gonna make your SVG morph work a breeze.

+
+ Start +
+
-

Well, we're going to set the morphIndex: 127 tween option and we will get an improved morph. Sometimes the recommended value isn't what we're looking for, so you just have to experience values around the recommended one. I also made a pen for you to play with.

-
- +

As you can see, the animation could need some fine tunning. Let's go ahead and play with the new utility, it's gonna make your SVG morph work a breeze.

+ +

Well, we're going to set the morphIndex: 127 tween option and we will get an improved morph. Sometimes the recommended value isn't what we're looking for, so you just have to experience values around the recommended one. I also + made a pen for you to play with.

+
+ - - -
- Start -
-
-

Much better! You can play with the morphIndex value, maybe you can get a more interesting morph.

- -

Morphing Polygon Paths

-

When your paths are only lineto, vertical-lineto and horizontal-lineto based shapes (the d attribute consists of L, V and H path commands), the SVG Plugin will work differently: it will use their points instead of sampling new ones. As a result, we boost the visual and maximize the performance. The morphPrecision option will not apply since the paths are already polygons, still you will have access to all the other options.

-

The plugin will try to convert paths to absolute values for polygons, but it might not find most accurate coordinates values for relative v and h path commands. I highly recommend using my utility converter to prepare your paths in that case.

-
// let's morph a triangle into a star
+                
+
+                
+ Start +
+
+

Much better! You can play with the morphIndex value, maybe you can get a more interesting morph.

+ +

Morphing Polygon Paths

+

When your paths are only lineto, vertical-lineto and horizontal-lineto based shapes (the d attribute consists of L, V and H path commands), the SVG + Plugin will work differently: it will use their points instead of sampling new ones. As a result, we boost the visual and maximize the performance. The morphPrecision option will not apply since the paths are already polygons, + still you will have access to all the other options.

+

The plugin will try to convert paths to absolute values for polygons, but it might not find most accurate coordinates values for relative v and h path commands. I highly recommend using my utility converter to prepare your paths in that case.

+
// let's morph a triangle into a star
 var tween1 = KUTE.to('#triangle', { path: '#star' }).start();
 
 // or same path into a square
 var tween2 = KUTE.to('#triangle', { path: '#square' }).start();
 
-

In the example below the triangle shape will morph into a square, then the square will morph into a star, so 2 tweens chained with a third that will morph back to the original triangle shape. For each tween the morph will use the number of points from the shape with most points as a sample size for the other shape. Let's have a look at the demo.

-
+

In the example below the triangle shape will morph into a square, then the square will morph into a star, so 2 tweens chained with a third that will morph back to the original triangle shape. For each tween the morph will use the number of + points from the shape with most points as a sample size for the other shape. Let's have a look at the demo.

+
+ + - - - + - + - -
- Start -
-
-

The morph for polygon paths is the best morph in terms of performance so it's worth keeping that in mind. Also using paths with only L path command will make sure to prevent value processing and allow the animation to start as fast as possible.

+ +
+ Start +
+
+

The morph for polygon paths is the best morph in terms of performance so it's worth keeping that in mind. Also using paths with only L path command will make sure to prevent value processing and allow the animation to start as + fast as possible.

-

Multi Path Example

-

In other cases, you may want to morph paths that have subpaths. Let's have a look at the following paths:

-
<svg id="multi-morph-example" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600">
-    <path d="M206.115,255.957c-23.854-12.259-47.043-18.479-68.94-18.479c-2.978,0-5.976,0.09-8.974,0.354 c-27.94,2.312-53.461,9.684-69.875,15.414c-4.354,1.599-8.817,3.288-13.415,5.152L0,414.096	c30.851-11.416,58.146-16.969,83.135-16.969c40.423,0,69.764,15.104,93.996,30.652c11.481-38.959,39.022-133.045,47.241-161.162 C218.397,262.975,212.334,259.332,206.115,255.957z 
-        M264.174,295.535l-45.223,157.074c13.416,7.686,58.549,32.024,93.105,32.024 c27.896,0,59.127-7.147,95.417-21.896l43.179-150.988c-29.316,9.461-57.438,14.26-83.732,14.26 C318.945,326.01,285.363,310.461,264.174,295.535z 
+            

Multi Path Example

+

In other cases, you may want to morph paths that have subpaths. Let's have a look at the following paths:

+
<svg id="multi-morph-example" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600">
+    <path d="M206.115,255.957c-23.854-12.259-47.043-18.479-68.94-18.479c-2.978,0-5.976,0.09-8.974,0.354 c-27.94,2.312-53.461,9.684-69.875,15.414c-4.354,1.599-8.817,3.288-13.415,5.152L0,414.096  c30.851-11.416,58.146-16.969,83.135-16.969c40.423,0,69.764,15.104,93.996,30.652c11.481-38.959,39.022-133.045,47.241-161.162 C218.397,262.975,212.334,259.332,206.115,255.957z
+        M264.174,295.535l-45.223,157.074c13.416,7.686,58.549,32.024,93.105,32.024 c27.896,0,59.127-7.147,95.417-21.896l43.179-150.988c-29.316,9.461-57.438,14.26-83.732,14.26 C318.945,326.01,285.363,310.461,264.174,295.535z
         M146.411,184.395c38.559,0.399,67.076,15.104,90.708,30.251l46.376-158.672c-9.772-5.598-35.403-19.547-53.929-24.3c-12.193-2.842-25.01-4.308-38.602-4.308c-25.898,0.488-54.194,6.973-86.444,19.9 L60.3,202.564c32.404-12.218,60.322-18.17,86.043-18.17C146.366,184.395,146.411,184.395,146.411,184.395L146.411,184.395z
         M512,99.062c-29.407,11.416-58.104,17.233-85.514,17.233c-45.844,0-79.646-15.901-101.547-31.183L278.964,244.23 c30.873,19.854,64.146,29.939,99.062,29.939c28.474,0,57.97-6.84,87.73-20.344l-0.091-1.111l1.867-0.443L512,99.062z"/>
      <path d="M0.175 256l-0.175-156.037 192-26.072v182.109z
         M224 69.241l255.936-37.241v224h-255.936z
         M479.999 288l-0.063 224-255.936-36.008v-187.992z
-        M192 471.918l-191.844-26.297-0.010-157.621h191.854z"/>   
+        M192 471.918l-191.844-26.297-0.010-157.621h191.854z"/>
 </svg>
 
-

As you can see, both these paths have subpaths, and KUTE.js will only animate the first of both in this case. To animate them all, we need to break them into multiple paths, so we can handle each path morph properly.

-
<svg id="multi-morph-example" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600">
+            

As you can see, both these paths have subpaths, and KUTE.js will only animate the first of both in this case. To animate them all, we need to break them into multiple paths, so we can handle each path morph properly.

+
<svg id="multi-morph-example" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600">
     <path id="w11" d="M206.115,255.957c-23.854-12.259-47.043-18.479-68.94-18.479c-2.978,0-5.976,0.09-8.974,0.354 c-27.94,2.312-53.461,9.684-69.875,15.414c-4.354,1.599-8.817,3.288-13.415,5.152L0,414.096 c30.851-11.416,58.146-16.969,83.135-16.969c40.423,0,69.764,15.104,93.996,30.652c11.481-38.959,39.022-133.045,47.241-161.162 C218.397,262.975,212.334,259.332,206.115,255.957z"/>
     <path id="w12" d="M264.174,295.535l-45.223,157.074c13.416,7.686,58.549,32.024,93.105,32.024 c27.896,0,59.127-7.147,95.417-21.896l43.179-150.988c-29.316,9.461-57.438,14.26-83.732,14.26 C318.945,326.01,285.363,310.461,264.174,295.535z"/>
     <path id="w13" d="M146.411,184.395c38.559,0.399,67.076,15.104,90.708,30.251l46.376-158.672c-9.772-5.598-35.403-19.547-53.929-24.3c-12.193-2.842-25.01-4.308-38.602-4.308c-25.898,0.488-54.194,6.973-86.444,19.9 L60.3,202.564c32.404-12.218,60.322-18.17,86.043-18.17C146.366,184.395,146.411,184.395,146.411,184.395L146.411,184.395z"/>
     <path id="w14" d="M512,99.062c-29.407,11.416-58.104,17.233-85.514,17.233c-45.844,0-79.646-15.901-101.547-31.183L278.964,244.23 c30.873,19.854,64.146,29.939,99.062,29.939c28.474,0,57.97-6.84,87.73-20.344l-0.091-1.111l1.867-0.443L512,99.062z"/>
-    
+
     <path id="w21" style="visibility:hidden" d="M0.175 256l-0.175-156.037 192-26.072v182.109z"/>
     <path id="w22" style="visibility:hidden" d="M224 69.241l255.936-37.241v224h-255.936z"/>
     <path id="w23" style="visibility:hidden" d="M479.999 288l-0.063 224-255.936-36.008v-187.992z"/>
-    <path id="w24" style="visibility:hidden" d="M192 471.918l-191.844-26.297-0.010-157.621h191.854z"/> 
+    <path id="w24" style="visibility:hidden" d="M192 471.918l-191.844-26.297-0.010-157.621h191.854z"/>
 </svg>
 
-

After a close inspection we determined that paths are not ordered the same so it seems we need to tween the paths in a way that their points travel the least possible distance, as follows: #w11 to #w24, #w13 to #w21, #w14 to #w22 and #w12 to #w23.

-

Now we can write the tween objects and get to working:

-
var multiMorph1 = KUTE.to('#w11', { path: '#w24' }).start();
+            

After a close inspection we determined that paths are not ordered the same so it seems we need to tween the paths in a way that their points travel the least possible distance, as follows: #w11 to #w24, #w13 to #w21, #w14 to #w22 and #w12 to #w23.

+

Now we can write the tween objects and get to working:

+
var multiMorph1 = KUTE.to('#w11', { path: '#w24' }).start();
 var multiMorph2 = KUTE.to('#w13', { path: '#w21' }).start();
 var multiMorph3 = KUTE.to('#w14', { path: '#w22' }).start();
 var multiMorph3 = KUTE.to('#w12', { path: '#w23' }).start();
 
-

As you can imagine, it's quite hard if not impossible to code something that would do all this work automatically, so after a minute or two tweaking the options, here's what we should see:

- -
- +

As you can imagine, it's quite hard if not impossible to code something that would do all this work automatically, so after a minute or two tweaking the options, here's what we should see:

+ +
+ - + - - -
- Start -
-
-

Note that this final touch required using reverseSecondPath:true option for all tweens because each shape have a slightly different position from its corresponding shape, so make sure to check the svg.js for a full code review.

- -

Complex Example

-

The last morph example is a bit more complex as the paths have subpaths with different positions and other important differences such as having different amounts of subpaths as well as significant differences of their positions. In this case you have to manually clone one or more paths in a way that the number of starting shapes is equal to the number of ending shapes, as well as making sure the starting shapes are close to their corresponding end shapes; at this point you should be just like in the previous example.

-

An important aspect of multi path morph is syncronization: since the .to() method will prepare the paths for interpolation at animation start, and this usually takes a bit of time, the problem can be easily solved as always using the .fromTo() method. So, let's get into it:

- -
// complex multi morph, the paths should be self explanatory
+                
+
+                
+ Start +
+
+

Note that this final touch required using reverseSecondPath:true option for all tweens because each shape have a slightly different position from its corresponding shape, so make sure to check the svg.js for a full code review.

+ +

Complex Example

+

The last morph example is a bit more complex as the paths have subpaths with different positions and other important differences such as having different amounts of subpaths as well as significant differences of their positions. In this case + you have to manually clone one or more paths in a way that the number of starting shapes is equal to the number of ending shapes, as well as making sure the starting shapes are close to their corresponding end shapes; at this point you + should be just like in the previous example.

+

An important aspect of multi path morph is syncronization: since the .to() method will prepare the paths for interpolation at animation start, and this usually takes a bit of time, the problem can be easily solved as always using + the .fromTo() method. So, let's get into it:

+ +
// complex multi morph, the paths should be self explanatory
 var morph1 = KUTE.fromTo('#start-container',  { path: '#start-container' },    { path: '#end-container' });
 var morph2 = KUTE.fromTo('#startpath1',       { path: '#startpath1' },         { path: '#endpath1' });
 var morph3 = KUTE.fromTo('#startpath1-clone', { path: '#startpath1-clone' },   { path: '#endpath1' });
 var morph4 = KUTE.fromTo('#startpath2',       { path: '#startpath2' },         { path: '#endpath2' });
 
-

As with the previous example, you should change which path will morph to which path so that their points travel the least possible distance and the morph animation looks visually appealing. In the next example, we have used a mask where we included the subpaths of both start and end shape, just to get the same visual as the originals.

-
- +

As with the previous example, you should change which path will morph to which path so that their points travel the least possible distance and the morph animation looks visually appealing. In the next example, we have used a mask where we included the subpaths of both start and end shape, just to get the same visual as the originals.

+
+ @@ -253,91 +275,109 @@ var morph4 = KUTE.fromTo('#startpath2', { path: '#startpath2' }, { - + - -
- Start -
-
-

So you have many options to improve the visual and performance for your complex animation ideas. The SVG Plugin for KUTE.js uses approximatelly the same algorithm as D3.js for determining the coordinates for tween, it's super light, it's a lighter script, it might be a better solution for your applications.

- -

Recommendations

-
    -
  • The SVG morph animation is very expensive so try to optimize the number of morph animations that run at the same time.
  • -
  • When morphing subpaths/multipaths instead of cloning shapes to have same number of shapes in both starting and ending shapes, you should also consider a fade and/or scale animation to improve the overal animation performance, don't forget about mobile devices.
  • -
  • Large displays would need best resolution possible so a small morphPrecision value (1-10) would be required, assuming performant hardware are powering the displays. For small displays you can get quite comfortable with almost any value, including the default value.
  • -
  • Polygons with only lineto path commands are best for performance.
  • -
  • Faster animation speed could be a great trick to hide any polygonal "artefacts". Strokes are also very useful for hiding the polygons' edges.
  • -
  • Don't forget about the path morph utility, it's gonna make your work a lot easier.
  • -
  • The SVG morph performance is the same for both .to() and .fromTo() methods, but the ones that use the second method will start faster, because the values have been prepared already and for the first method the processing of the two paths happens on tween start delaying the animation, so keep that in mind when working with syncing multiple tweens, the .to() based morph will always start later. Of course this assumes the you cache the tween objects first and start the animation later, if not (you start the animation on object creation), both methods will be delayed.
  • -
- -

Drawing Stroke

-

Next, we're going to animate the stroking of some elements. Starting with KUTE.js version 1.5.2, along with <path> shapes, <circle>, <ellipse>, <rect>, <line>, <polyline> and <polygon> shapes are also supported; the script uses the SVG standard .getTotalLength() method for <path> shapes, while the others use some helper methods. Here some code examples:

-
// draw the stroke from 0-10% to 90-100%
+
+                
+ Start +
+
+

So you have many options to improve the visual and performance for your complex animation ideas. The SVG Plugin for KUTE.js uses approximatelly the same algorithm as D3.js for determining the coordinates for tween, it's super light, it's a + lighter script, it might be a better solution for your applications.

+ +

Recommendations

+
    +
  • The SVG morph animation is very expensive so try to optimize the number of morph animations that run at the same time.
  • +
  • When morphing subpaths/multipaths instead of cloning shapes to have same number of shapes in both starting and ending shapes, you should also consider a fade and/or scale animation to improve the overal animation performance, don't forget + about mobile devices.
  • +
  • Large displays would need best resolution possible so a small morphPrecision value (1-10) would be required, assuming performant hardware are powering the displays. For small displays you can get quite comfortable with almost + any value, including the default value.
  • +
  • Polygons with only lineto path commands are best for performance.
  • +
  • Faster animation speed could be a great trick to hide any polygonal "artefacts". Strokes are also very useful for hiding the polygons' edges.
  • +
  • Don't forget about the path morph utility, it's gonna make your work a lot easier.
  • +
  • The SVG morph performance is the same for both .to() and .fromTo() methods, but the ones that use the second method will start faster, because the values have been prepared already and for the first method the + processing of the two paths happens on tween start delaying the animation, so keep that in mind when working with syncing multiple tweens, the .to() based morph will always start later. Of course this assumes the you cache + the tween objects first and start the animation later, if not (you start the animation on object creation), both methods will be delayed.
  • +
+ +

Drawing Stroke

+

Next, we're going to animate the stroking of some elements. Starting with KUTE.js version 1.5.2, along with <path> shapes, <circle>, <ellipse>, <rect>, <line>, + <polyline> and <polygon> shapes are also supported; the script uses the SVG standard .getTotalLength() method for <path> shapes, while the others use some helper methods. Here + some code examples:

+
// draw the stroke from 0-10% to 90-100%
 var tween1 = KUTE.fromTo('selector1',{draw:'0% 10%'}, {draw:'90% 100%'});
-    
+
 // draw the stroke from zero to full path length
 var tween2 = KUTE.fromTo('selector1',{draw:'0% 0%'}, {draw:'0% 100%'});
-    
+
 // draw the stroke from full length to 50%
 var tween3 = KUTE.fromTo('selector1',{draw:'0% 100%'}, {draw:'50% 50%'});
 
-

We're gonna chain these tweens and start the animation real quick.

-
- - - - - - - -
- Start -
-
-

Remember: the draw property also accepts absolute values, eg. draw: '0 150'; the .to() method takes 0% 100% as start value for your tweens when stroke-dasharray and stroke-dashoffset are not set.

- -

SVG Transforms

-

Starting with KUTE.js 1.5.2, the SVG Plugin features a new tween property for cross browser SVG transforms, but was coded as a separate set of methods for SVG only, to keep performance tight and solve most browser inconsistencies. A very simple roadmap was described here; in brief we needed to find a way to enable SVG transforms in a reliable and cross-browser supported fashion.

-

With KUTE.js 1.6.0 the SVG transform is a bigger part of the SVG Plugin for two reasons: first is the ability to use the transformOrigin just like for CSS3 transforms and secondly the unique way to normalize translation to work with the transform origin in a way that the animation is just as consistent as for CSS3 transforms on non-SVG elements. Also the value processing is consistent with the working draft.

-

While you can still use regular CSS3 transforms for SVGs on browsers like Google Chrome, Opera and others, Firefox struggles big time with the percentage based transform-origin values and ALL Internet Explorer versions have no implementation for CSS3 transforms on SVG elements.

-

KUTE.js SVG Plugin comes with a better way to animate transforms on SVGs shapes reliably on all browsers, by the use of the transform presentation attribute and the svgTransform tween property with a special notation:

+

We're gonna chain these tweens and start the animation real quick.

+
+ + + + + + + +
+ Start +
+
+

Remember: the draw property also accepts absolute values, eg. draw: '0 150'; the .to() method takes 0% 100% as start value for your tweens when stroke-dasharray and stroke-dashoffset are not set.

-
// using the svgTransform property works in all SVG enabled browsers
-var tween2 = KUTE.to('shape', {svgTransform: { translate: [150,100], rotate: 45, skewX: 15, skewY: 20, scale: 1.5 }}); 
+            

SVG Transforms

+

Starting with KUTE.js 1.5.2, the SVG Plugin features a new tween property for cross browser SVG transforms, but was coded as a separate set of methods for SVG only, to keep performance tight and solve most browser inconsistencies. A very simple + roadmap was described here; in brief we needed to find a way to enable SVG transforms in a reliable and cross-browser supported fashion.

+

With KUTE.js 1.6.0 the SVG transform is a bigger part of the SVG Plugin for two reasons: first is the ability to use the transformOrigin just like for CSS3 transforms and secondly the unique way to normalize translation to work + with the transform origin in a way that the animation is just as consistent as for CSS3 transforms on non-SVG elements. Also the value processing is consistent with the working draft.

+

While you can still use regular CSS3 transforms for SVGs on browsers like Google Chrome, Opera and others, Firefox struggles big time with the percentage based transform-origin values and ALL Internet + Explorer versions have no implementation for CSS3 transforms on SVG elements.

+

KUTE.js SVG Plugin comes with a better way to animate transforms on SVGs shapes reliably on all browsers, by the use of the transform presentation attribute and the svgTransform tween property with + a special notation:

+ +
// using the svgTransform property works in all SVG enabled browsers
+var tween2 = KUTE.to('shape', {svgTransform: { translate: [150,100], rotate: 45, skewX: 15, skewY: 20, scale: 1.5 }});
 
 // regular CSS3 transforms apply to SVG elements but not all browsers fully/partially supported
 var tween1 = KUTE.to('shape', { translate: [150,100], rotate: 45, skewX: 15, skewY: 20, scale: 1.5 }, { transformOrigin: '50% 50%' });
 
-

As you can see we have some familiar notation, but an important notice here is that svgTransform tween property treat all SVG transform functions as if you are using the 50% 50% of the shape box at all times by default, even if the default value is "0px 0px 0px" on SVGs in most browsers.

-

Perhaps the most important thing to remember is the fact that SVG tranformations always use SVG coordinates system, and the transform attribute accepts no measurement units such as degrees or pixels. For these reasons the transformOrigin tween option can also accept array values just in case you need coordinates relative to the parent <svg> element. Also values like top left values will work.

-

In the following examples we showcase the animation of CSS3 transform applied to SVG shapes (LEFT) as well as svgTransform based animations (RIGHT). I highly encourage you to test all of them in all browsers, and as a word ahead, animations in Webkit browsers will look identical, while others are inconsistent or not responding to DOM changes. Let's break it down to pieces.

+

As you can see we have some familiar notation, but an important notice here is that svgTransform tween property treat all SVG transform functions as if you are using the 50% 50% of the shape box + at all times by default, even if the default value is "0px 0px 0px" on SVGs in most browsers.

+

Perhaps the most important thing to remember is the fact that SVG tranformations always use SVG coordinates system, and the transform attribute accepts no measurement units such as degrees or pixels. For these reasons the transformOrigin tween option can also accept array values just in case you need coordinates relative to the parent <svg> element. Also values like top left values will work.

+

In the following examples we showcase the animation of CSS3 transform applied to SVG shapes (LEFT) as well as svgTransform based animations (RIGHT). I highly encourage you to test all of them in all browsers, + and as a word ahead, animations in Webkit browsers will look identical, while others are inconsistent or not responding to DOM changes. Let's break it down to pieces.

-

SVG Rotation

-

Our first chapter of the SVG transform is all about rotations, perhaps the most important part here. As of with KUTE.js 1.6.0 the svgTransform will only accept single value for the angle value rotate: 45, the rotation will go around the shape's center point by default, again, contrary to the browsers' default value and you can set a transformOrigin tween option to override the behavior.

-

The argument for this implementation is that this is something you would expect from regular HTML elements rotation and probably most needed, not to mention the amount of savings in the codebase department. Let's have a look at a quick demo:

-
- - - +

SVG Rotation

+

Our first chapter of the SVG transform is all about rotations, perhaps the most important part here. As of with KUTE.js 1.6.0 the svgTransform will only accept single value for the angle value rotate: 45, + the rotation will go around the shape's center point by default, again, contrary to the browsers' default value and you can set a transformOrigin tween option to override the behavior.

+

The argument for this implementation is that this is something you would expect from regular HTML elements rotation and probably most needed, not to mention the amount of savings in the codebase department. Let's have a look at a quick demo:

+
+ + + - -
- Start -
-
-

The first tween uses the CSS3 transform notation and the animation clearly shows the shape rotating around it's center coordinate, as we've set transformOrigin option to 50% 50%, but this animation doesn't work in IE browsers, while in Firefox is inconsistent with the SVG coordinate system. The second tween uses the rotate: 360 notation and the animation shows the shape rotating around it's own central point and without any option, an animation that DO WORK in all SVG enabled browsers.

-

When for CSS3 transforms we could have used values such as center bottom as transform-origin (also not supported in all modern browsers for SVGs), the entire processing was basically in/by the browser, however when it comes to SVGs the plugin here will compute the transformOrigin tween setting value accordingly to use a shape's .getBBox() value to determine for instance the coordinates for 25% 75% position or center top.

-

In other cases you may want to rotate shapes around the center point of the parent <svg> or <g> element, and we use it's .getBBox() to determine the 50% 50% coordinate, so here's how to deal with it:

+
+ Start +
+
+

The first tween uses the CSS3 transform notation and the animation clearly shows the shape rotating around it's center coordinate, as we've set transformOrigin option to 50% 50%, but this animation doesn't work in IE browsers, + while in Firefox is inconsistent with the SVG coordinate system. The second tween uses the rotate: 360 notation and the animation shows the shape rotating around it's own central point and without any option, an animation + that DO WORK in all SVG enabled browsers.

+

When for CSS3 transforms we could have used values such as center bottom as transform-origin (also not supported in all modern browsers for SVGs), the entire processing was basically in/by the browser, however when it comes + to SVGs the plugin here will compute the transformOrigin tween setting value accordingly to use a shape's .getBBox() value to determine for instance the coordinates for 25% 75% position or center top.

-
// rotate around parent svg's "50% 50%" coordinate as transform-origin
+            

In other cases you may want to rotate shapes around the center point of the parent <svg> or <g> element, and we use it's .getBBox() to determine the 50% 50% coordinate, so here's how to deal + with it:

+ +
// rotate around parent svg's "50% 50%" coordinate as transform-origin
 // get the bounding box of the parent element
 var svgBB = element.ownerSVGElement.getBBox(); // returns an object of the parent <svg> element
 
@@ -355,154 +395,175 @@ var svgOriginY = svgBB.height * 50 / 100 - translation[1];
 var rotationTween = KUTE.to(element, {svgTransform: {rotate: 150}}, { transformOrigin: [svgOriginX, svgOriginY]} );
 
-
- - - - - -
- Start -
-
-

Note that this is the only SVG transform example in which we have adapted the transform-origin for the CSS3 transform rotation so that both animations look consistent in all browsers, and if you are interested in learning about this fix, similar to the above, just we are adding "px" to the calculated value, but you better make sure to check svg.js file.

- -

SVG Translation

-

In this example we'll have a look at translations, so when setting translate: [150,0], the first value is X (horizontal) coordinate to which the shape will translate to and the second value is Y (vertical) coordinate for translation. When translate: 150 notation is used, the script will understand that's the X value and the Y value is 0 just like for the regular HTML elements transformation. Let's have a look at a quick demo:

-
- - - - - -
- Start -
-
-

The first tween uses the CSS3 translate: 580 notation for the end value, while the second tween uses the translate: [0,0] as svgTransform value. For the second example the values are unitless and are relative to the viewBox attribute.

- -

SVG Skew

-

For skews for SVGs we have a very simple notation: skewX: 25 or skewY: -25 as SVGs don't support the skew: [X,Y] function. Here's a quick demo:

-
- - - - - -
- Start -
-
-

The first tween skews the shape on both X and Y axis in a chain via regular CSS3 transforms and the second tween skews the shape on X and Y axis via the svgTransform tween property. You will notice translation kicking in to set the transform origin and the example also showcases the fact that chain transformations for SVGs via transform attribute works just as for the CSS3 transformations.

- -

SVG Scaling

-

Another transform example for SVGs is the scale. Unlike translations, for scale animation the plugin only accepts single value like scale: 1.5, for both X (horizontal) axis and Y (vertical) axis, to keep it simple and even if SVGs do support scale(X,Y). But because the scaling on SVGs depends very much on the shape's position, the script will always try to adjust the translation to make the animation look as we would expect. A quick demo:

-
- - - +
+ + + -
- Start -
-
-

The first tween scales the shape at scale: 1.5 via regular CSS3 transforms, and the second tween scales down the shape at scale: 0.5 value via svgTransform. If you inspect the elements, you will notice for the second shape translation is involved, and this is to keep transform-origin at an expected 50% 50% value. A similar case as with the skews.

+
+ Start +
+
+

Note that this is the only SVG transform example in which we have adapted the transform-origin for the CSS3 transform rotation so that both animations look consistent in all browsers, and if you are interested in learning about + this fix, similar to the above, just we are adding "px" to the calculated value, but you better make sure to check svg.js file.

-

SVG Mixed Transform Functions

-

Our last transform example for SVGs is the mixed transformation. Just like for the other examples the plugin will try to adjust the rotation transform-origin to make it look as you would expect it from regular HTML elements. Let's combine 3 functions at the same time and see what happens:

-
- - - +

SVG Translation

+

In this example we'll have a look at translations, so when setting translate: [150,0], the first value is X (horizontal) coordinate to which the shape will translate to and the second value is Y (vertical) coordinate for translation. + When translate: 150 notation is used, the script will understand that's the X value and the Y value is 0 just like for the regular HTML elements transformation. Let's have a look at a quick demo:

+
+ + + - -
- Start -
-
-

Both shapes are scaled at scale: 1.5, translated to translate: 250 and skewed at skewX: -15. If you inspect the elements, you will notice the second shape's translation is different from what we've set in the tween object, and this is to keep transform-origin at an expected 50% 50% value. This means that the plugin will also compensate rotation transform origin when skews are used, so that both CSS3 transform property and SVG transform attribute have an identical animation.

- -

Chained SVG transforms

-

The SVG Plugin does not work with SVG specific chained transform functions right away (do not confuse with tween chain), but if your SVGs only use this feature to set a custom transform-origin, it should look like this:

-
<svg>
+
+                
+ Start +
+
+

The first tween uses the CSS3 translate: 580 notation for the end value, while the second tween uses the translate: [0,0] as svgTransform value. For the second example the values are + unitless and are relative to the viewBox attribute.

+ +

SVG Skew

+

For skews for SVGs we have a very simple notation: skewX: 25 or skewY: -25 as SVGs don't support the skew: [X,Y] function. Here's a quick demo:

+
+ + + + + +
+ Start +
+
+

The first tween skews the shape on both X and Y axis in a chain via regular CSS3 transforms and the second tween skews the shape on X and Y axis via the svgTransform tween property. You will notice translation + kicking in to set the transform origin and the example also showcases the fact that chain transformations for SVGs via transform attribute works just as for the CSS3 transformations.

+ +

SVG Scaling

+

Another transform example for SVGs is the scale. Unlike translations, for scale animation the plugin only accepts single value like scale: 1.5, for both X (horizontal) axis and Y (vertical) axis, to keep it simple and even if + SVGs do support scale(X,Y). But because the scaling on SVGs depends very much on the shape's position, the script will always try to adjust the translation to make the animation look as we would expect. A quick demo:

+
+ + + + + +
+ Start +
+
+

The first tween scales the shape at scale: 1.5 via regular CSS3 transforms, and the second tween scales down the shape at scale: 0.5 value via svgTransform. If you inspect the elements, + you will notice for the second shape translation is involved, and this is to keep transform-origin at an expected 50% 50% value. A similar case as with the skews.

+ +

SVG Mixed Transform Functions

+

Our last transform example for SVGs is the mixed transformation. Just like for the other examples the plugin will try to adjust the rotation transform-origin to make it look as you would expect it from regular HTML elements. Let's + combine 3 functions at the same time and see what happens:

+
+ + + + + +
+ Start +
+
+

Both shapes are scaled at scale: 1.5, translated to translate: 250 and skewed at skewX: -15. If you inspect the elements, you will notice the second shape's translation is different from what we've set + in the tween object, and this is to keep transform-origin at an expected 50% 50% value. This means that the plugin will also compensate rotation transform origin when skews are used, so that both CSS3 transform property + and SVG transform attribute have an identical animation.

+ +

Chained SVG transforms

+

The SVG Plugin does not work with SVG specific chained transform functions right away (do not confuse with tween chain), but if your SVGs only use this feature to set a custom transform-origin, it should look like this:

+
<svg>
     <circle transform="translate(150,150) rotate(45) scale(1.2) translate(-150,-150)" r="20"></circle>
 </svg>
 
-

Well in this case I would recommend using the values of the first translation as transform-origin for your tween built with the .fromTo() method like so:

-
// a possible workaround for animating a SVG element that uses chained transform functions
-KUTE.fromTo(element, 
+            

Well in this case I would recommend using the values of the first translation as transform-origin for your tween built with the .fromTo() method like so:

+
// a possible workaround for animating a SVG element that uses chained transform functions
+KUTE.fromTo(element,
     {svgTransform : { translate: 0, rotate: 45, scale: 0.5 }}, // we asume the current translation is zero on both X & Y axis
     {svgTransform : { translate: 450, rotate: 0, scale: 1.5 }}, // we will translate the X to a 450 value and scale to 1.5
     {transformOrigin: [256,256]} // tween options use the transform-origin of the target SVG element
 ).start();
 
-

Before you hit the Start button, make sure to check the transform attribute value.

-
- - Before you hit the Start button, make sure to check the transform attribute value.

+
+ + + transform="translate(256,256) rotate(45) scale(0.5) translate(-256,-256)"> - -
- Start -
-
-

This way we make sure to count the real current transform-origin and produce a consistent animation with the SVG coordinate system, just as the above example showcases.

-

Recommendations for SVG Transforms

-
    -
  • The SVG Plugin coming with KUTE.js version 1.6.0 is successfuly handling all possible combinations of transform functions, and always uses same order of transform functions: translate, rotate, skewX, skewY and scale to keep animation consistent and with same aspect as for CSS3 transforms on non-SVG elements.
  • -
  • Keep in mind that the SVG transforms will use the center of a shape as transform origin by default, contrary to the SVG draft.
  • -
  • Keep in mind the adjustments required for rotations, remember the .getBBox() method, it's really useful to set custom transform-origin.
  • -
  • By default browsers use overflow: hidden for <svg> so child elements are partialy/completely hidden while animating. You might want to set overflow: visible or some browser specific tricks if that is the case.
  • -
  • When using viewBox="0 0 500 500" attribute for <svg> and no width and/or height attribute(s), means that you expect the SVG to be scalable and most Internet Explorer versions simply don't work. You might want to check this tutorial.
  • -
  • Similar to the CSS3 transform animation featured in the core engine, the svgTransform property DOES stack transform functions for chained tween objects created with the .to() method, you will have to provide only values for the functions that will change and the plugin will try to keep the unchanged values. However, there's a catch: you need to follow all the properties and I highly recommend checking the example code for skews in the svg.js file.
  • -
  • In other cases when you need maximum control and precision or when shapes are already affected by translation, you might want to use the .fromTo() method with all proper values.
  • -
  • Also the svgTransform tween property does not support 3D transforms, because they are not supported in all SVG enabled browsers.
  • +
    + Start +
    +
+

This way we make sure to count the real current transform-origin and produce a consistent animation with the SVG coordinate system, just as the above example showcases.

+ +

Recommendations for SVG Transforms

+
    +
  • The SVG Plugin coming with KUTE.js version 1.6.0 is successfuly handling all possible combinations of transform functions, and always uses same order of transform functions: translate, rotate, skewX, + skewY and scale to keep animation consistent and with same aspect as for CSS3 transforms on non-SVG elements.
  • +
  • Keep in mind that the SVG transforms will use the center of a shape as transform origin by default, contrary to the SVG draft.
  • +
  • Keep in mind the adjustments required for rotations, remember the .getBBox() method, it's really useful to set custom transform-origin.
  • +
  • By default browsers use overflow: hidden for <svg> so child elements are partialy/completely hidden while animating. You might want to set overflow: visible or some browser specific tricks if that + is the case.
  • +
  • When using viewBox="0 0 500 500" attribute for <svg> and no width and/or height attribute(s), means that you expect the SVG to be scalable and most Internet Explorer versions simply + don't work. You might want to check this tutorial.
  • +
  • Similar to the CSS3 transform animation featured in the core engine, the svgTransform property DOES stack transform functions for chained tween objects created with the .to() method, you will + have to provide only values for the functions that will change and the plugin will try to keep the unchanged values. However, there's a catch: you need to follow all the properties and I highly recommend checking the example code for + skews in the svg.js file.
  • +
  • In other cases when you need maximum control and precision or when shapes are already affected by translation, you might want to use the .fromTo() method with all proper values.
  • +
  • Also the svgTransform tween property does not support 3D transforms, because they are not supported in all SVG enabled browsers.
  • +
+ + +

SVG Plugin Tips

+
    +
  • The SVG Plugin can be combined with the Attributes Plugin to enable even more advanced/complex animations for SVG elements.
  • +
  • Since SVG morph scripting works only with path or glyph elements, you might need a convertToPath feature, so check this out.
  • +
+ +
+ + + + -

SVG Plugin Tips

-
    -
  • The SVG Plugin can be combined with the Attributes Plugin to enable even more advanced/complex animations for SVG elements.
  • -
  • Since SVG morph scripting works only with path or glyph elements, you might need a convertToPath feature, so check this out.
  • -
-
- - - - - - -
- + - - + - - + + - - - - - - + + + + + + + + + + + - \ No newline at end of file + + diff --git a/demo/text.html b/demo/text.html index d4b60eb..fb98d55 100644 --- a/demo/text.html +++ b/demo/text.html @@ -3,7 +3,9 @@ - + + + @@ -12,164 +14,181 @@ - + + KUTE.js Text Plugin | Javascript Animation Engine - + - + - + - - - + + + - - - - - + + + + + -
- -
- - +
-
-

Text Plugin

-

The KUTE.js Text Plugin extends the core engine and enables animation for text elements in two ways: either incrementing or decreasing a number in a given string or writing a string character by character with a very cool effect.

+
-
// basic synthax for number increments
+        
+
+        
+

Text Plugin

+

The KUTE.js Text Plugin extends the core engine and enables animation for text elements in two ways: either incrementing or decreasing a number in a given string or writing a string character by character with a very cool effect.

+ +
// basic synthax for number increments
 var myNumberTween = KUTE.to('selector', {number: 1500}); // this assumes it will start from current number or from 0
 
 // OR text writing character by character
 var myTextTween = KUTE.to('selector', {text: 'A text string with other <span>substring</span> should do.'});
 
-

The effects of these two properties are very popular, but pay attention to the fact that every 16 miliseconds the browser has to parse the HTML structure around your target elements so caution is advised. With other words, try to limit the number of simultaneus text animations.

- -

Number Incrementing/Decreasing

-

In the first example, let's animate a number, approximatelly as written above:

-
-

Total number of lines: 0

- -
- Start -
-
-

The button action will toggle the valuesEnd value for the number property, because tweening a number to itself would produce no effect.

- -

Writing Text

-

This feature come with a additional tween option called textChars for the scrambling text character:

-
    -
  • alpha use lowercase alphabetical characters, the default value
  • -
  • upper use UPPERCASE alphabetical characters
  • -
  • numeric use numerical characters
  • -
  • symbols use symbols such as #, $, %, etc.
  • -
  • all use all alpha numeric and symbols.
  • -
  • YOUR CUSTOM STRING use your own custom characters; eg: 'KUTE.JS IS #AWESOME'.
  • -
-
-

Click the Start button on the right.

- -
- Start -
-
-

Keep in mind that the yoyo feature will NOT un-write / delete character by character the string, but will write the previous text instead.

- -

Combining Both

-
-
-
-

0

-
-
-

Clicks so far?

-
-
-
- Start -
-
-

In this example we've used the textChars option with symbols and all values respectively, but combining the two text properties and some other KUTE.js features can really spice up some content. Have fun!

- - -
+

The effects of these two properties are very popular, but pay attention to the fact that every 16 miliseconds the browser has to parse the HTML structure around your target elements so caution is advised. With other words, try to limit the + number of simultaneus text animations.

- - +

Number Incrementing/Decreasing

+

In the first example, let's animate a number, approximatelly as written above:

+
+

Total number of lines: 0

-
- +
+ Start +
+
+

The button action will toggle the valuesEnd value for the number property, because tweening a number to itself would produce no effect.

+ +

Writing Text

+

This feature come with a additional tween option called textChars for the scrambling text character:

+
    +
  • alpha use lowercase alphabetical characters, the default value
  • +
  • upper use UPPERCASE alphabetical characters
  • +
  • numeric use numerical characters
  • +
  • symbols use symbols such as #, $, %, etc.
  • +
  • all use all alpha numeric and symbols.
  • +
  • YOUR CUSTOM STRING use your own custom characters; eg: 'KUTE.JS IS #AWESOME'.
  • +
+
+

Click the Start button on the right.

+ +
+ Start +
+
+

Keep in mind that the yoyo feature will NOT un-write / delete character by character the string, but will write the previous text instead.

+ +

Combining Both

+
+
+
+

0

+
+
+

Clicks so far?

+
+
+
+ Start +
+
+

In this example we've used the textChars option with symbols and all values respectively, but combining the two text properties and some other KUTE.js features can really spice up some content. Have fun!

+ + +
+ + + + +
+ - - + - - + + - - - - - + + + + + + + + + - \ No newline at end of file + +