forked from darsain/motio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmotio.js
528 lines (484 loc) · 12.2 KB
/
motio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/*!
* Motio 2.2.1 - 18th Apr 2013
* https://github.com/Darsain/motio
*
* Licensed under the MIT license.
* http://opensource.org/licenses/MIT
*/
;(function(w, undefined){
'use strict';
var className = 'Motio';
// Local WindowAnimationTiming interface polyfill
var cAF = w.cancelAnimationFrame || w.cancelRequestAnimationFrame;
var rAF = w.requestAnimationFrame;
(function () {
var vendors = ['moz', 'webkit', 'o'];
var lastTime = 0;
// For a more accurate WindowAnimationTiming interface implementation, ditch the native
// requestAnimationFrame when cancelAnimationFrame is not present (older versions of Firefox)
for(var i = 0, l = vendors.length; i < l && !cAF; ++i) {
cAF = w[vendors[i]+'CancelAnimationFrame'] || w[vendors[i]+'CancelRequestAnimationFrame'];
rAF = cAF && w[vendors[i]+'RequestAnimationFrame'];
}
if (!cAF) {
rAF = function (callback) {
var currTime = +new Date();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
lastTime = currTime + timeToCall;
return w.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
};
cAF = function (id) {
clearTimeout(id);
};
}
}());
/**
* Motio.
*
* @class
*
* @param {Element} element DOM element with animation background.
* @param {Object} options Object with plugin options.
* @param {Object} callbackMap Callbacks map.
*/
function Motio(element, options) {
// Options
var o = defaults(options);
// Private variables
var self = this;
var isPan = !o.frames;
var frames = [];
var callbacks = {};
var animation = {};
var active = 0;
var pos, bgPos, lastPos, frameID, renderID, i, l;
// Exposed properties
self.element = element;
self.width = o.width || element.clientWidth;
self.height = o.height || element.clientHeight;
self.options = o;
self.isPaused = true;
/**
* Pause animation.
*
* @return {Object} Motio instance.
*/
self.pause = function () {
// frameID can be timeout, or animationFrame ID
cAF(frameID);
clearTimeout(frameID);
frameID = 0;
if (!self.isPaused) {
self.isPaused = true;
trigger('pause');
}
return self;
};
/**
* Play animation.
*
* @param {Boolean} reversed Reversed animation.
*
* @return {Object} Motio instance.
*/
self.play = function (reversed) {
animation.finite = false;
animation.callback = undefined;
animation.immediate = false;
resume(reversed);
return self;
};
/**
* Request rendering when paused.
*
* @param {Boolean} reversed Reversed animation.
*
* @return {Void}
*/
function resume(reversed) {
animation.reversed = reversed;
if (!frameID) {
self.isPaused = false;
trigger('play');
requestRender();
}
}
/**
* Toggle animation.
*
* @return {Object} Motio instance.
*/
self.toggle = function () {
self[frameID ? 'pause' : 'play']();
return self;
};
/**
* Animate to the first frame and pause.
*
* @param {Boolean} immediate Reposition immediately without animation.
* @param {Function} callback Execute a callback on arrival.
*
* @return {Object} Motio instance.
*/
self.toStart = function (immediate, callback) {
return self.to(0, immediate, callback);
};
/**
* Animate to the last frame and pause.
*
* @param {Boolean} immediate Reposition immediately without animation.
* @param {Function} callback Execute a callback on arrival.
*
* @return {Object} Motio instance.
*/
self.toEnd = function (immediate, callback) {
return self.to(frames.length - 1, immediate, callback);
};
/**
* Animate to a specified frame index and pause.
*
* @param {Integer} frame Frame index starting at 0.
* @param {Boolean} immediate Reposition immediately without animation.
* @param {Function} callback Execute a callback on arrival.
*
* @return {Object} Motio instance.
*/
self.to = function (frame, immediate, callback) {
if (isPan || !isNumber(frame) || frame < 0 || frame >= frames.length) {
return self;
}
// Handle optional argument
if (type(immediate) === 'function') {
callback = immediate;
immediate = false;
}
// Handle cases where the requested animation is already active
if (frame === active) {
if (frame === 0) {
active = frames.length;
} else if (frame === frames.length - 1) {
active = -1;
} else {
if (type(callback) === 'function') {
callback.call(self);
}
self.pause();
return self;
}
}
// Update animation object
animation.finite = true;
animation.to = frame;
animation.immediate = !!immediate;
animation.callback = callback;
// Resume rendering if paused
resume();
return self;
};
/**
* Determine position for next frame.
*
* @return {Void}
*/
function positionTick() {
if (isPan) {
pos.x += o.speedX / o.fps;
pos.y += o.speedY / o.fps;
if (o.bgWidth && Math.abs(pos.x) > o.bgWidth) {
pos.x = pos.x % o.bgWidth;
}
if (o.bgHeight && Math.abs(pos.y) > o.bgHeight) {
pos.y = pos.y % o.bgHeight;
}
} else {
if (animation.finite) {
if (animation.immediate) {
active = animation.to;
} else {
active += active > animation.to ? -1 : 1;
}
} else {
if (animation.reversed) {
if (--active <= 0) {
active = frames.length - 1;
}
} else {
if (++active >= frames.length) {
active = 0;
}
}
}
// Update active frame property
self.frame = active;
}
}
/**
* Render animation frame.
*
* @return {Void}
*/
function render() {
// Reset renderID
renderID = 0;
// Prepare new background position
bgPos = isPan ? Math.round(pos.x) + 'px ' + Math.round(pos.y) + 'px' : frames[active];
// Update the position only when there is a change
// to not cause redundant reflows & repaints
if (bgPos !== lastPos) {
element.style.backgroundPosition = lastPos = bgPos;
}
// Trigger frame event
trigger('frame');
// When arrived to a finite animation destination, pause & execute the callback
if (animation.finite && animation.to === active) {
self.pause();
if (type(animation.callback) === 'function') {
animation.callback.call(self);
}
}
}
/**
* Render rAF wrapper.
*
* @return {Int} Animation frame index.
*/
function requestRender() {
if (!(animation.finite && animation.to === active)) {
if (animation.immediate) {
frameID = 0;
} else {
if (o.fps >= 60) {
frameID = rAF(requestRender);
} else {
frameID = setTimeout(requestRender, 1000 / o.fps);
}
}
positionTick();
if (!renderID) {
renderID = rAF(render);
}
}
}
/**
* Update one of the dynamic option properties.
*
* Only these options can be updated:
* speed, fps
*
* @param {String} option Option name.
* @param {Mixed} value New option value.
*
* @return {Object} Motio instance.
*/
self.set = function (option, value) {
o[option] = value;
return self;
};
/**
* Registers callbacks.
*
* @param {Mixed} name Event name, or callbacks map.
* @param {Mixed} fn Callback, or an array of callback functions.
*
* @return {Object} Motio instance.
*/
self.on = function (name, fn) {
// Callbacks map
if (type(name) === 'object') {
for (var key in name) {
if (name.hasOwnProperty(key)) {
self.on(key, name[key]);
}
}
// Callback
} else if (type(fn) === 'function') {
var names = name.split(' ');
for (var n = 0, nl = names.length; n < nl; n++) {
callbacks[names[n]] = callbacks[names[n]] || [];
if (callbackIndex(names[n], fn) === -1) {
callbacks[names[n]].push(fn);
}
}
// Callbacks array
} else if (type(fn) === 'array') {
for (var f = 0, fl = fn.length; f < fl; f++) {
self.on(name, fn[f]);
}
}
return self;
};
/**
* Remove one or all callbacks.
*
* @param {String} name Event name.
* @param {Mixed} fn Callback, or an array of callback functions. Omit to remove all callbacks.
*
* @return {Object} Motio instance.
*/
self.off = function (name, fn) {
if (fn instanceof Array) {
for (var f = 0, fl = fn.length; f < fl; f++) {
self.off(name, fn[f]);
}
} else {
var names = name.split(' ');
for (var n = 0, nl = names.length; n < nl; n++) {
callbacks[names[n]] = callbacks[names[n]] || [];
if (type(fn) === 'undefined') {
callbacks[names[n]].length = 0;
} else {
var index = callbackIndex(names[n], fn);
if (index !== -1) {
callbacks[names[n]].splice(index, 1);
}
}
}
}
return self;
};
/**
* Returns callback array index.
*
* @param {String} name Event name.
* @param {Function} fn Function
*
* @return {Int} Callback array index, or -1 if isn't registered.
*/
function callbackIndex(name, fn) {
for (i = 0, l = callbacks[name].length; i < l; i++) {
if (callbacks[name][i] === fn) {
return i;
}
}
return -1;
}
/**
* Trigger callbacks for event.
*
* @param {String} name Event name.
* @param {Mixed} argX Arguments passed to callbacks.
*
* @return {Void}
*/
function trigger(name, arg1) {
if (callbacks[name]) {
for (i = 0, l = callbacks[name].length; i < l; i++) {
callbacks[name][i].call(self, name, arg1);
}
}
}
/**
* Returns a computed style property of a frame element.
*
* @param {String} name Property name.
*
* @return {String}
*/
function getProp(name) {
return w.getComputedStyle ? w.getComputedStyle(element, null)[name] : element.currentStyle[name];
}
/**
* Destroy plugin instance and reset backgroundPosition to its original state
*
* @public
*/
self.destroy = function () {
self.pause();
element.style.backgroundPosition = '';
return self;
};
/**
* Construct.
*/
(function () {
// Background position
var posString = (
getProp('backgroundPosition') ||
getProp('backgroundPositionX') + ' ' + getProp('backgroundPositionY')
).replace(/left|top/gi, 0).split(' ');
pos = {
x: getInt(posString[0]),
y: getInt(posString[1])
};
// Build frames array
if (!isPan) {
frames.length = 0;
for (var i = 0; i < o.frames; i++) {
if (o.vertical) {
pos.y = i * -self.height;
} else {
pos.x = i * -self.width;
}
frames.push(pos.x + 'px ' + pos.y + 'px');
}
// Expose sprite mode properties
self.frames = frames.length;
self.frame = 0;
} else {
// Expose panning mode properties
self.pos = pos;
}
}());
}
/**
* Return type of the value.
*
* @param {Mixed} value
*
* @return {String}
*/
function type(value) {
return Object.prototype.toString.call(value).match(/\s([a-z]+)/i)[1].toLowerCase();
}
/**
* Check if variable is a number.
*
* @param {Mixed} value
*
* @return {Boolean}
*/
function isNumber(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
}
/**
* Fills unassigned option properties with default values. Does 1 level deep object clone.
*
* @param {Object} options
*
* @return {Void}
*/
function defaults(options) {
var output = {};
options = type(options) === 'object' ? options : {};
for (var key in Motio.defaults) {
output[key] = (options.hasOwnProperty(key) ? options : Motio.defaults)[key];
}
return output;
}
/**
* Parse integer out of a string.
*
* @param {Mixed} value
*
* @return {Int}
*/
function getInt(value) {
return 0 | parseInt(value, 10);
}
// Expose class globally
w[className] = Motio;
// Default options
Motio.defaults = {
fps: 15, // Frames per second.
// Sprite animation specific options
frames: 0, // Number of frames in sprite.
vertical: 0, // Tells Motio that you are using vertically stacked sprite image.
width: 0, // Set the frame width manually (optional).
height: 0, // Set the frame height manually (optional).
// Panning specific options
speedX: 0, // Horizontal panning speed in pixels per second.
speedY: 0, // Vertical panning speed in pixels per second.
bgWidth: 0, // Width of the background image (optional).
bgHeight: 0 // Height of the background image (optional).
};
})(window);