/
catepilla.js
452 lines (364 loc) · 11.9 KB
/
catepilla.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
/**
* Catepilla v1.0.00
* Make that image gallery get all wiggly
* https://github.com/nclud/catepilla
* Requires Modernizr 2.5 and requestAnimationFrame polyfill
*/
/*jshint asi: false, curly: true, eqeqeq: true, forin: false, newcap: true, noempty: true, strict: true, undef: true, browser: true */
(function( window, undefined ) {
'use strict';
// get global vars
var document = window.document;
var Modernizr = window.Modernizr;
// get convienent vars
var transformProp = Modernizr.prefixed('transform');
var transformCSSProp = {
'WebkitTransform': '-webkit-transform',
'MozTransform': '-moz-transform',
'msTransform': '-ms-transform',
'OTransform': '-o-transform',
'transform': 'transform'
}[ transformProp ];
var durationProp= Modernizr.prefixed('transitionDuration');
var delayProp = Modernizr.prefixed('transitionDelay');
var transitionProp = Modernizr.prefixed('transition');
var transitionPropertyProp = Modernizr.prefixed('transition-property');
var positionElem = Modernizr.csstransforms3d ? function( elem, x, y ) {
elem.style[ transformProp ] = 'translate3d(' + x + 'px, ' + y + 'px, 0)';
} : Modernizr.csstransforms ? function( elem, x, y ) {
elem.style[ transformProp ] = 'translate(' + x + 'px, ' + y + 'px)';
} : function( elem, x, y ) {
elem.style.left = x + 'px';
elem.style.top = y + 'px';
};
var transEndEventName = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
}[ transitionProp ];
var TWO_PI = Math.PI * 2;
// -------------------------- Catepilla -------------------------- //
/**
* @class Creates a new Catepilla gallery
* @param elem {Element} - The list element which contains images
* @param options {Object} - Optional options
*/
function Catepilla( elem, options ) {
if ( !elem ) {
return;
}
this.list = elem;
this.options = {};
for ( var prop in Catepilla.defaults ) {
this.options[ prop ] = Catepilla.defaults[ prop ];
}
for ( prop in options ) {
this.options[ prop ] = options[ prop ];
}
// default properties
this.selectedIndex = -1;
this.images = [];
this.wiggleSpeed = 0;
// used to keep track of images that have been loaded
this.imagesData = {};
this.create();
}
Catepilla.defaults = {
segmentCount: 5,
height: 300,
segmentHeight: 0.55,
transitionDuration: 0.2,
perSegmentDelay: 0.05,
wiggleAcceleration: 0.001,
maxWiggleSpeed: 0.1,
wiggleDelay: 1000,
isAutoAdvancing: true,
startAngle: Math.PI
};
/**
* creates gallery
*/
Catepilla.prototype.create = function() {
// create elem to hold segments
this.elem = document.createElement('div');
this.elem.className = 'catepilla';
this.height = this.options.height;
this.elem.style.height = this.height + 'px';
// add elem to DOM
this.list.parentNode.insertBefore( this.elem, this.list.nextSibling );
// hide original list elem
this.list.style.display = 'none';
// get width
this.width = this.elem.offsetWidth;
this._createSegments();
this.hide();
// add images
var images = this.list.getElementsByTagName('img');
var src;
for ( var i=0, len = images.length; i < len; i++ ) {
src = images[i].src;
this.addImage( src );
}
// show first image
this.setSelectedIndex( 0 );
};
/**
* @param {String} src - The src or URL of an image
*/
Catepilla.prototype.addImage = function( src ) {
// don't proceed if already added
if ( this.imagesData[ src ] ) {
return;
}
// load image
var img = new Image();
img.addEventListener( 'load', this, false );
// create object to keep track of its properties
this.imagesData[ src ] = {
index: this.images.length // backwards reference for this.images
};
// add to images
this.images.push( img );
// set src, which will trigger ._loadHander()
img.src = src;
};
Catepilla.prototype._createSegments = function() {
var segmentCount = this.options.segmentCount;
this.segmentWidth = Math.floor( this.width / segmentCount );
this.segments = [];
var segment;
var frag = document.createDocumentFragment();
for ( var i=0; i < segmentCount; i++ ) {
segment = new CatepillaSegment({
parent: this,
width: this.segmentWidth,
index: i
});
frag.appendChild( segment.elem );
this.segments.push( segment );
}
this.elem.appendChild( frag );
};
/**
* Trigger a method on each segment in the instance
* @param {String} methodName
*/
Catepilla.prototype.segmentsEach = function( methodName ) {
var segment;
// pass in any other arguments after methodName
var args = Array.prototype.slice.call( arguments, 1 );
for (var i=0, len = this.segments.length; i < len; i++) {
segment = this.segments[i];
segment[ methodName ].apply( segment, args );
}
};
/**
* reveal
* @param {integer} index
*/
Catepilla.prototype.setSelectedIndex = function( index ) {
// don't proceed if not a new index
if ( index === this.selectedIndex || index < 0 || index > this.images.length - 1 ) {
return;
}
// console.log('⚑ setting selected index', index );
// get img data of selected image
var src = this.images[ index ].src;
var imgData = this.imagesData[ src ];
this.selectedIndex = index;
// stop animation, if any
this.stopAnimation();
// do fun stuff async, after transition
var _this = this;
var setIndexAfterHidden = function() {
// reset segments y position
_this.theta = _this.options.startAngle;
_this.segmentsEach('setWiggleY');
if ( imgData.isLoaded ) {
_this._setSelectedImage();
} else {
imgData.callback = _this._setSelectedImage;
}
};
var delay = ( this.options.transitionDuration +
this.options.perSegmentDelay * this.segments.length ) * 1000;
if ( this.isHidden ) {
// if already hidden, change to it now
setIndexAfterHidden();
} else {
// hide, then change after hidden
this.hide();
setTimeout( setIndexAfterHidden, delay );
}
};
Catepilla.prototype._setSelectedImage = function( index ) {
// console.log('★set selected image★');
var img = this.images[ this.selectedIndex ];
this.segmentsEach( 'setImage', img );
this.show();
// start animation
this.setAnimationTimeout( this.options.wiggleDelay, this.startAnimation );
};
Catepilla.prototype.show = function() {
if ( !this.isHidden ) {
return;
}
this.segmentsEach('show');
this.isHidden = false;
};
Catepilla.prototype.hide = function( callback ) {
if ( this.isHidden ) {
return;
}
this.segmentsEach('hide');
this.isHidden = true;
this.stopAnimation();
};
/**
* advance to next image
**/
Catepilla.prototype.next = function() {
var index = ( this.selectedIndex + 1 ) % this.images.length;
this.setSelectedIndex( index );
};
// ----- animation ----- //
/**
* set a setTimeout for a frame of animation
* @param {Integer} delay - Delay of animation in milliseconds
* @param {Function} animation - Function triggered for a frame of animation
*/
Catepilla.prototype.setAnimationTimeout = function( delay, animation ) {
if ( this.animationTimeout ) {
clearTimeout( this.animationTimeout );
}
this.animationTimeout = setTimeout( animation.bind( this ), delay );
};
Catepilla.prototype.startAnimation = function() {
if ( this.isAnimating ) {
return;
}
this.isAnimating = true;
this.isAccelerating = true;
this.segmentsEach( 'setTransitionsEnabled', false );
this.wiggle();
};
Catepilla.prototype.wiggle = function() {
// console.log('wiggle');
this.wiggleAcceleration = this.isAccelerating ? this.options.wiggleAcceleration : this.deceleration;
this.wiggleSpeed += this.wiggleAcceleration;
this.wiggleSpeed = Math.max( 0, Math.min( this.options.maxWiggleSpeed, this.wiggleSpeed ) );
// apply rotation
this.theta += this.wiggleSpeed;
// normalize angle
this.theta = ( this.theta + TWO_PI * 2 ) % TWO_PI;
this.segmentsEach('setWiggleY');
this.segmentsEach('position');
// if speed has reach it's maximum
if ( this.isAccelerating && this.wiggleSpeed === this.options.maxWiggleSpeed ) {
this.startDeceleration();
}
if ( !this.isAccelerating && this.wiggleSpeed === 0 ) {
// if animation has stopped
this.stopAnimation();
// after wiggle ends, switch to the next image, after delay
if ( this.options.isAutoAdvancing ) {
this.setAnimationTimeout( this.options.wiggleDelay, this.next );
}
} else if ( this.isAnimating ) {
// keep on wiggling
this.animationFrameId = window.requestAnimationFrame( this.wiggle.bind( this ) );
}
};
Catepilla.prototype.startDeceleration = function() {
this.isAccelerating = false;
var speed = this.wiggleSpeed;
var rotations = Math.ceil( speed / 0.05 );
// return to original angle
var destinationAngle = TWO_PI * rotations + this.options.startAngle;
this.deceleration = -( speed * speed ) / ( 2 * ( destinationAngle - this.theta ) + speed );
};
Catepilla.prototype.stopAnimation = function() {
// console.log('stopping animation');
this.isAccelerating = false;
this.wiggleSpeed = 0;
// disable css transtiions
this.segmentsEach( 'setTransitionsEnabled', true );
this.isAnimating = false;
if ( this.animationTimeout ) {
clearTimeout( this.animationTimeout );
}
if ( isFinite( this.animationFrameId ) ) {
window.cancelAnimationFrame( this.animationFrameId );
delete this.animationFrameId;
}
};
// ----- event handling ----- //
Catepilla.prototype.handleEvent = function( event ) {
var handleMethod = '_' + event.type + 'Handler';
if ( this[ handleMethod ] ) {
this[ handleMethod ]( event );
}
};
// triggered after img loads
Catepilla.prototype._loadHandler = function( event ) {
var img = event.target;
var imgData = this.imagesData[ img.src ];
imgData.isLoaded = true;
// trigger callback
if ( imgData.callback ) {
imgData.callback.call( this );
delete imgData.callback;
}
};
// put in global namespace
window.Catepilla = Catepilla;
// -------------------------- CatepillaSegment -------------------------- //
function CatepillaSegment( props ) {
// extend props over segment, width, imgSrc, index
for ( var prop in props ) {
this[ prop ] = props[ prop ];
}
var opts = this.parent.options;
this.elem = document.createElement('div');
this.elem.className = 'segment';
this.elem.style.width = this.width + 'px';
this.elem.style.height = ( 100 * opts.segmentHeight ) + '%';
this.elem.style[ durationProp ] = opts.transitionDuration + 's';
this.elem.style[ delayProp ] = ( opts.perSegmentDelay * this.index ) + 's';
this.img = new Image();
this.position();
this.setTransitionsEnabled( true );
this.elem.appendChild( this.img );
}
CatepillaSegment.prototype.setWiggleY = function() {
var parent = this.parent;
this.y = ( Math.sin( this.index * Math.PI / 2 + parent.theta ) * 0.5 + 0.5 ) *
parent.height * ( 1 - parent.options.segmentHeight );
};
CatepillaSegment.prototype.position = function() {
positionElem( this.elem, this.width * this.index, this.y );
positionElem( this.img, this.width * -this.index, -this.y + this.imgOffsetY );
};
CatepillaSegment.prototype.setImage = function( img ) {
this.img.src = img.src;
this.img.width = this.parent.width;
var sizeRatio = this.parent.width / img.width;
this.imgOffsetY = ( this.parent.height - img.height * sizeRatio ) / 2;
positionElem( this.img, this.width * -this.index, -this.y + this.imgOffsetY );
};
CatepillaSegment.prototype.hide = function() {
this.elem.style.opacity = 0;
var sign = Math.random() > 0.5 ? 1 : -1;
var hideY = this.parent.height * 1.5 * sign + this.parent.height / 2;
positionElem( this.elem, this.width * this.index, hideY );
};
CatepillaSegment.prototype.show = function() {
this.elem.style.opacity = 1;
this.position();
};
CatepillaSegment.prototype.setTransitionsEnabled = function( enabled ) {
this.elem.style[ transitionPropertyProp ] = enabled ? transformCSSProp + ', opacity' : 'none';
};
})( window );