Javascript small animation components and implementation code _ php Digest

Source: Internet
Author: User
Javascript small animation components and implementation code. if you want to learn javascript animation, refer. The idea is indeed very practical. How does js complete a normal animation? let's take a look at the example.

The code is as follows:


SetInterval (function (){
Element. style. left = parseFloat (element. style. left) + (n) + 'px ';
}, 10 );


<P id = "test2" style = "border: 0px solid #00ff00; position: absolute; left: 0px; top: 400px; background: #0f0 "> test </p> script var element = document. getElementById ("test2"); setInterval (function () {element. style. left = parseFloat (element. style. left) + 2 + 'px ';}, 10); script
[Ctrl + A Select All Note: If you need to introduce external Js, you need to refresh it to execute]


Use the window. setInterval animation function to execute an animation every 10 milliseconds;
The clearInterval function is used to end the animation.
Every setInterval operation returns a value similar to the thread id;
Var interval = setInterval (function (){
Element. style. left = parseFloat (element. style. left) + (n) + 'px ';
}, 10 );
ClearInterval (interval) can be used to end animation playback.
Interval = setInterval (function (){
If (parseFloat (element. style. left)> 500) clearInterval (interval)
Element. style. left = parseFloat (element. style. left) + 2 + 'px ';
}, 10 );
When the size exceeds PX, the animation will stop and the element will not move.

<P id = "test2" style = "border: 0px solid #00ff00; position: absolute; left: 0px; top: 400px; background: #0f0 "> test </p> script var element = document. getElementById ('test2'); interval = setInterval (function () {if (parseFloat (element. style. left)> 500) clearInterval (interval) element. style. left = parseFloat (element. style. left) + 2 + 'px ';}, 10); script
[Ctrl + A Select All Note: If you need to introduce external Js, you need to refresh it to execute]


However, the above animation is relatively stiff, and we have another timeline animation.
Example:
Var element = document. getElementById ('test1 ');
Var start = + new Date, dur = 1000, finish = start + dur;
Interval = setInterval (function (){
Var time = + new Date,
Pos = time> finish? 1: (time-start)/dur;
Element. style. left = (100 * pos) + "px ";
If (time> finish ){
ClearInterval (interval );
}
}, 10 );
Start is the start time of the target animation (+ new Date is actually new Date (). getTime ())
The time required for animation execution
Finish is the end time of the target animation.
Pos = time> finish? 1: (time-start)/dur; // pos can be imagined as a frequency, with a time ratio
(100 * pos), 100 indicates the distance. if the distance is 500 PX, it is set to * pos;
Time> finish: if it exceeds the time limit, the animation will be stopped!

<P id = "test2" style = "border: 0px solid #00ff00; position: absolute; left: 0px; top: 400px; background: #0f0 "> test </p> script var element = document. getElementById ('test2'); var start = + new Date, dur = 1000, finish = start + dur; interval = setInterval (function () {var time = + new Date, pos = time> finish? 1: (time-start)/dur; element. style. left = (100 * pos) + "px"; if (time> finish) {clearInterval (interval) ;}, 10); script
[Ctrl + A Select All Note: If you need to introduce external Js, you need to refresh it to execute]


Good. now we know how to write a simple animation.
Let's take a look at how a small and complete animation component is written:

The code is as follows:


(Function ($, name ){
Var parseEl = document. createElement ('P ')
,
Props = ('backgroundcolor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+
'Borderrightcolor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontsize' +
'Fontweight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxheight' +
'Maxwidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingleft' +
'Paddingright paddingTop right textIndent top width wordSpacing zindex'). split ('')
,
Normalize = function (style ){
Var css,
Rules = {},
I = props. length,
V;
ParseEl. innerHTML ='

';
Css = parseEl. childNodes [0]. style;
While (I --) if (v = css [props [I]) rules [props [I] = parse (v );
Return rules;
},
Color = function (source, target, pos ){
Var I = 2, j, c, tmp, v = [], r = [];
While (j = 3, c = arguments [i-1], I --)
If (s (c, 0) = 'r') {c = c. match (/\ d +/g); while (j --) v. push (~~ C [j]);} else {
If (c. length = 4) c = '#' + s (c, 1) + s (c, 1) + s (c, 2) + s (c, 2) + s (c, 3) + s (c, 3 );
While (j --) v. push (parseInt (s (c, 1 + j * 2), 16 ));}
While (j --) {tmp = ~~ (V [j + 3] + (v [j]-v [j + 3]) * pos); r. push (tmp <0? 0: tmp> 255? 255: tmp );}
Return 'rgb ('+ r. join (', ') + ')';
},
Parse = function (prop ){
Var p = parseFloat (prop), q = prop. replace (/^ [\-\ d \.] + /,'');
Return isNaN (p )? {V: q, f: color, u: ''}:{ v: p, f: interpolate, u: q };
},
S = function (str, p, c ){
Return str. substr (p, c | 1); // used for color
},
Interpolate = function (source, target, pos ){
Return (source + (target-source) * pos). toFixed (3 );
},
Flower = function (el, style, opts, after ){
Var el = document. getElementById (el), // Obtain the element object through id
Opts = opts | | {},
Target = normalize (style ),
Comp = el. currentStyle? El. currentStyle: getComputedStyle (el, null), // Compatible with w3c, ie, get style
Prop,
Current = {},
Start = + new Date, // start time
Dur = opts. duration | 200, // executes the event. the default value is 200.
Finish = start + dur, // end time
Interval,
Easing = opts. easing | function (pos) {return (-Math. cos (pos * Math. PI)/2) + 0.5 ;};
For (prop in target) current [prop] = parse (comp [prop]);
Interval = setInterval (function (){
Var time = + new Date,
Pos = time> finish? 1: (time-start)/dur;
For (prop in target ){
El. style [prop] = target [prop]. f (current [prop]. v, target [prop]. v, easing (pos) + target [prop]. u;
}
If (time> finish ){
ClearInterval (interval); opts. after & opts. after (); after & setTimeout (after, 1 );
}
}, 10 );
};
$ [Name] = flower;
}) (Window, "flower ");


The code is as follows:


Var parse = function (prop ){
Var p = parseFloat (prop), q = prop. replace (/^ [\-\ d \.] + /,'');
Return isNaN (p )? {V: q, f: color, u: ''}:{ v: p, f: interpolate, u: q };
}
Var p = parseFloat (prop) means: 500px => 500;
Q = prop. replace (/^ [\-\ d \.] +/, ''); 500px => px;
Return isNaN (p )? {V: q, f: color, u: ''}:{ v: p, f: interpolate, u: q }; it means that if the color value is obtained (because it has #), {v: q, f: color, u: ''} u is returned, f is a color function (which will be discussed later );
Var s = function (str, p, c) {return str. substr (p, c | 1 );}


The s function is used to intercept a string and return the final result.
The color function returns the color value in the format of rgb (x, x, x ).
The normalize function returns a json object containing the css attribute name and value to be executed by the element.
While (I --) if (v = css [props [I]) rules [props [I] = parse (v );
Split a line of code to see how it works.
While (I --){
// Here A = sign is used, and the value assignment operation is performed first. if the value does not exist, if it does not exist, it will not pass. The result is as follows :)
If (v = css [props [I]) {
Rules [props [I] = parse (v); // assign to a new object,
}
}
Return (source + (target-source) * pos). toFixed (3 );
ToFixed is used to solve the decimal problem, for example, 0.000000001; it will become 1e-9; it is not the expected result. toFixed can be used to solve it. toFixed (n), where n represents the number of digits after the decimal point.
El. currentStyle? El. currentStyle: getComputedStyle (el, null );
This is actually compatible with multiple browsers. for details about the code for getting elements, refer to: get final style in JS [getStyle]
Four el target objects of flower, style is the final style, opts, and callbak that includes parameter options (dur time, easing slow function, run after ), 4th after is the last callbak executed;
Opts. easing can use various easing algorithms to change the motion of elements;
For example

The code is as follows:


Function bounce (pos ){
If (pos <(1/2. 75 )){
Return (7.5625 * pos );
} Else if (pos <(2/2. 75 )){
Return (7.5625 * (pos-= (1.5/2.75) * pos +. 75 );
} Else if (pos <(2.5/2.75 )){
Return (7.5625 * (pos-= (2.25/2.75) * pos +. 9375 );
} Else {
Return (7.5625 * (pos-= (2.625/2.75) * pos +. 984375 );
}
}
(Function ($, name ){
Window. flower = flower;
}) (Window, 'flower ');


In this way, internal functions are free and only one interface is exposed through this call. Otherwise, the functions outside will not be able to access the flower in anonymous correspondence;
Let's take a look at the call example :)

The code is as follows:


Test


Test


Script
(Function ($, name ){
Var parseEl = document. createElement ('P ')
,
Props = ('backgroundcolor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+
'Borderrightcolor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontsize' +
'Fontweight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxheight' +
'Maxwidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingleft' +
'Paddingright paddingTop right textIndent top width wordSpacing zindex'). split ('')
,
Normalize = function (style ){
Var css,
Rules = {},
I = props. length,
V;
ParseEl. innerHTML ='

';
Css = parseEl. childNodes [0]. style;
While (I --) if (v = css [props [I]) rules [props [I] = parse (v );
Return rules;
},
Color = function (source, target, pos ){
Var I = 2, j, c, tmp, v = [], r = [];
While (j = 3, c = arguments [i-1], I --)
If (s (c, 0) = 'r') {c = c. match (/\ d +/g); while (j --) v. push (~~ C [j]);} else {
If (c. length = 4) c = '#' + s (c, 1) + s (c, 1) + s (c, 2) + s (c, 2) + s (c, 3) + s (c, 3 );
While (j --) v. push (parseInt (s (c, 1 + j * 2), 16 ));}
While (j --) {tmp = ~~ (V [j + 3] + (v [j]-v [j + 3]) * pos); r. push (tmp <0? 0: tmp> 255? 255: tmp );}
Return 'rgb ('+ r. join (', ') + ')';
},
Parse = function (prop ){
Var p = parseFloat (prop), q = prop. replace (/^ [\-\ d \.] + /,'');
Return isNaN (p )? {V: q, f: color, u: ''}:{ v: p, f: interpolate, u: q };
},
S = function (str, p, c ){
Return str. substr (p, c | 1 );
},
Interpolate = function (source, target, pos ){
Return (source + (target-source) * pos). toFixed (3 );
},
Flower = function (el, style, opts, after ){
Var el = document. getElementById (el ),
Opts = opts | | {},
Target = normalize (style ),
Comp = el. currentStyle? El. currentStyle: getComputedStyle (el, null ),
Prop,
Current = {},
Start = + new Date,
Dur = opts. duration | 200,
Finish = start + dur,
Interval,
Easing = opts. easing | function (pos) {return (-Math. cos (pos * Math. PI)/2) + 0.5 ;};
For (prop in target) current [prop] = parse (comp [prop]);
Interval = setInterval (function (){
Var time = + new Date,
Pos = time> finish? 1: (time-start)/dur;
For (prop in target ){
El. style [prop] = target [prop]. f (current [prop]. v, target [prop]. v, easing (pos) + target [prop]. u;
}
If (time> finish ){
ClearInterval (interval); opts. after & opts. after (); after & setTimeout (after, 1 );
}
}, 10 );
};
$ [Name] = flower;
}) (Window, "flower ");
(Function (){
Var bounce = function (pos ){
If (pos <(1/2. 75 )){
Return (7.5625 * pos );
} Else if (pos <(2/2. 75 )){
Return (7.5625 * (pos-= (1.5/2.75) * pos +. 75 );
} Else if (pos <(2.5/2.75 )){
Return (7.5625 * (pos-= (2.25/2.75) * pos +. 9375 );
} Else {
Return (7.5625 * (pos-= (2.625/2.75) * pos +. 984375 );
}
}
Flower ('test2', 'left: 300px; padding: 10px; border: 50px solid # ff0000 ',{
Duration: 1500,
After: function (){
Flower ('test1', 'background: #0f0; left: 100px; padding-bottom: 100px; opacity: 1 ',{
Duration: 1234, easing: bounce
});
}
});
})();
Script


Reference: http://scripty2.com/doc/scripty2%20fx/s2/fx/transitions.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.