forked from JoelBesada/scrollpath
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.scrollpath.js
More file actions
643 lines (547 loc) · 18.4 KB
/
Copy pathjquery.scrollpath.js
File metadata and controls
643 lines (547 loc) · 18.4 KB
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/*
=============================
jQuery Scroll Path Plugin
v1.1.1
Demo and Documentation:
http://joelb.me/scrollpath
=============================
A jQuery plugin for defining a custom path that the browser
follows when scrolling. Comes with a custom scrollbar,
which is styled in scrollpath.css.
Author: Joel Besada (http://www.joelb.me)
Date: 2012-02-01
Copyright 2012, Joel Besada
MIT Licensed (http://www.opensource.org/licenses/mit-license.php)
*/
( function ( $, window, document, undefined ) {
var PREFIX = "-" + getVendorPrefix().toLowerCase() + "-",
HAS_TRANSFORM_SUPPORT = supportsTransforms(),
HAS_CANVAS_SUPPORT = supportsCanvas(),
FPS = 60,
STEP_SIZE = 50, // Number of actual path steps per scroll steps.
// The extra steps are needed to make animations look smooth.
BIG_STEP_SIZE = STEP_SIZE * 5, // Step size for space, page down/up
isInitiated = false,
isDragging = false,
isAnimating = false,
step,
pathObject,
pathList,
element,
scrollBar,
scrollHandle,
// Default speeds for scrolling and rotating (with path.rotate())
speeds = {
scrollSpeed: 50,
rotationSpeed: Math.PI/15
},
// Default plugin settings
settings = {
wrapAround: false,
drawPath: false,
scrollBar: true
},
methods = {
/* Initates the plugin */
init: function( options ) {
if ( this.length > 1 || isInitiated ) $.error( "jQuery.scrollPath can only initialized on *one* element *once*" );
$.extend( settings, options );
isInitiated = true;
element = this;
pathList = pathObject.getPath();
initCanvas();
initScrollBar();
scrollToStep( 0 ); // Go to the first step immediately
element.css( "position", "relative" );
$( document ).on({
"mousewheel": scrollHandler,
"DOMMouseScroll": scrollHandler, // Firefox
"keydown": keyHandler,
"mousedown": function( e ) {
if( e.button === 1 ) {
e.preventDefault();
return false;
}
}
});
$( window ).on( "resize", function() { scrollToStep( step ); } ); // Re-centers the screen
return this;
},
getPath: function( options ) {
$.extend( speeds, options );
return pathObject || ( pathObject = new Path( speeds.scrollSpeed, speeds.rotationSpeed ));
},
scrollTo: function( name, duration, easing, callback ) {
var destination = findStep( name );
if ( destination === undefined ) $.error( "jQuery.scrollPath could not find scroll target with name '" + name + "'" );
var distance = destination - step;
if ( settings.wrapAround && Math.abs( distance ) > pathList.length / 2) {
if ( destination > step) {
distance = -step - pathList.length + destination;
} else {
distance = pathList.length - step + destination;
}
}
animateSteps( distance, duration, easing, callback );
return this;
}
};
/* The Path object serves as a context to "draw" the scroll path
on before initating the plugin */
function Path( scrollS, rotateS ) {
var PADDING = 40,
scrollSpeed = scrollS,
rotationSpeed = rotateS,
xPos = 0,
yPos = 0,
rotation = 0,
width = 0,
height = 0,
offsetX = 0,
offsetY = 0,
canvasPath = [{ method: "moveTo", args: [ 0, 0 ] }], // Needed if first path operation isn't a moveTo
path = [],
nameMap = {},
defaults = {
rotate: null,
callback: null,
name: null
};
/* Rotates the screen while staying in place */
this.rotate = function( radians, options ) {
var settings = $.extend( {}, defaults, options ),
rotDistance = Math.abs( radians - rotation ),
steps = Math.round( rotDistance / rotationSpeed ) * STEP_SIZE,
rotStep = ( radians - rotation ) / steps,
i = 1;
if ( !HAS_TRANSFORM_SUPPORT ) {
if ( settings.name || settings.callback ) {
// In case there was a name or callback set to this path, we add an extra step with those
// so they don't get lost in browsers without rotation support
this.moveTo(xPos, yPos, {
callback: settings.callback,
name: settings.name
});
}
return this;
}
for( ; i <= steps; i++ ) {
path.push({ x: xPos,
y: yPos,
rotate: rotation + rotStep * i,
callback: i === steps ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
rotation = radians % ( Math.PI*2 );
return this;
};
/* Moves (jumps) directly to the given point */
this.moveTo = function( x, y, options ) {
var settings = $.extend( {}, defaults, options ),
steps = path.length ? STEP_SIZE : 1;
i = 0;
for( ; i < steps; i++ ) {
path.push({ x: x,
y: y,
rotate: settings.rotate !== null ? settings.rotate : rotation,
callback: i === steps - 1 ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
setPos( x, y );
updateCanvas( x, y );
canvasPath.push({ method: "moveTo", args: arguments });
return this;
};
/* Draws a straight path to the given point */
this.lineTo = function( x, y, options ) {
var settings = $.extend( {}, defaults, options ),
relX = x - xPos,
relY = y - yPos,
distance = hypotenuse( relX, relY ),
steps = Math.round( distance/scrollSpeed ) * STEP_SIZE,
xStep = relX / steps,
yStep = relY / steps,
canRotate = settings.rotate !== null && HAS_TRANSFORM_SUPPORT,
rotStep = ( canRotate ? ( settings.rotate - rotation ) / steps : 0 ),
i = 1;
for ( ; i <= steps; i++ ) {
path.push({ x: xPos + xStep * i,
y: yPos + yStep * i,
rotate: rotation + rotStep * i,
callback: i === steps ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
rotation = ( canRotate ? settings.rotate : rotation );
setPos( x, y );
updateCanvas( x, y );
canvasPath.push({ method: "lineTo", args: arguments });
return this;
};
/* Draws an arced path with a given circle center, radius, start and end angle. */
this.arc = function( centerX, centerY, radius, startAngle, endAngle, counterclockwise, options ) {
var settings = $.extend( {}, defaults, options ),
startX = centerX + Math.cos( startAngle ) * radius,
startY = centerY + Math.sin( startAngle ) * radius,
endX = centerX + Math.cos( endAngle ) * radius,
endY = centerY + Math.sin( endAngle ) * radius,
angleDistance = sectorAngle( startAngle, endAngle, counterclockwise ),
distance = radius * angleDistance,
steps = Math.round( distance/scrollSpeed ) * STEP_SIZE,
radStep = angleDistance / steps * ( counterclockwise ? -1 : 1 ),
canRotate = settings.rotate !== null && HAS_TRANSFORM_SUPPORT,
rotStep = ( canRotate ? (settings.rotate - rotation) / steps : 0 ),
i = 1;
// If the arc starting point isn't the same as the end point of the preceding path,
// prepend a line to the starting point. This is the default behavior when drawing on
// a canvas.
if ( xPos !== startX || yPos !== startY ) {
this.lineTo( startX, startY );
}
for ( ; i <= steps; i++ ) {
path.push({ x: centerX + radius * Math.cos( startAngle + radStep*i ),
y: centerY + radius * Math.sin( startAngle + radStep*i ),
rotate: rotation + rotStep * i,
callback: i === steps ? settings.callback : null
});
}
if( settings.name ) nameMap[ settings.name ] = path.length - 1;
rotation = ( canRotate ? settings.rotate : rotation );
setPos( endX, endY );
updateCanvas( centerX + radius, centerY + radius );
updateCanvas( centerX - radius, centerY - radius );
canvasPath.push({ method: "arc", args: arguments });
return this;
};
this.getPath = function() {
return path;
};
this.getNameMap = function() {
return nameMap;
};
/* Appends offsets to all x and y coordinates before returning the canvas path */
this.getCanvasPath = function() {
var i = 0;
for( ; i < canvasPath.length; i++ ) {
canvasPath[ i ].args[ 0 ] -= this.getPathOffsetX();
canvasPath[ i ].args[ 1 ] -= this.getPathOffsetY();
}
return canvasPath;
};
this.getPathWidth = function() {
return width - offsetX + PADDING;
};
this.getPathHeight = function() {
return height - offsetY + PADDING;
};
this.getPathOffsetX = function() {
return offsetX - PADDING / 2;
};
this.getPathOffsetY = function() {
return offsetY - PADDING / 2;
};
/* Sets the current position */
function setPos( x, y ) {
xPos = x;
yPos = y;
}
/* Updates width and height, if needed */
function updateCanvas( x, y ) {
offsetX = Math.min( x, offsetX );
offsetY = Math.min( y, offsetY );
width = Math.max( x, width );
height = Math.max( y, height );
}
}
/* Plugin wrapper, handles method calling */
$.fn.scrollPath = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) );
} else if ( typeof method === "object" || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error( "Method " + method + " does not exist on jQuery.scrollPath" );
}
};
/* Initalize the scroll bar */
function initScrollBar() {
if ( !settings.scrollBar ) return;
// TODO: Holding down the mouse on the bar should "rapidfire", like holding down space
scrollBar = $( "<div>" ).
addClass( "sp-scroll-bar" ).
on( "mousedown", function( e ) {
var clickStep = Math.round( (e.offsetY || e.clientY) / scrollBar.height() * ( pathList.length - 1) );
// Close in on the clicked part instead of jumping directly to it.
// This mimics the default browser scroll bar behavior.
if ( Math.abs(clickStep - step) > BIG_STEP_SIZE) {
clickStep = step + ( 5 * STEP_SIZE * ( clickStep > step ? 1 : -1 ) );
}
scrollToStep(clickStep);
e.preventDefault();
return false;
});
scrollHandle = $( "<div>" ).
addClass( "sp-scroll-handle" ).
on({
click: function( e ) {
e.preventDefault();
return false;
},
mousedown: function( e ) {
if ( e.button !== 0 ) return;
isDragging = true;
e.preventDefault();
return false;
}
});
$( document ).on({
mouseup: function( e ) { isDragging = false; },
mousemove: function( e ) { if( isDragging ) dragScrollHandler( e ); }
});
$( "body" ).prepend( scrollBar.append( scrollHandle ) );
}
/* Initializes the path canvas */
function initCanvas() {
if ( !settings.drawPath || !HAS_CANVAS_SUPPORT ) return;
var canvas,
style = {
position: "absolute",
"z-index": 9998,
left: pathObject.getPathOffsetX(),
top: pathObject.getPathOffsetY(),
"pointer-events": "none"
};
applyPrefix( style, "user-select", "none" );
applyPrefix( style, "user-drag", "none" );
canvas = $( "<canvas>" ).
addClass( "sp-canvas" ).
css( style ).
prependTo( element );
canvas[ 0 ].width = pathObject.getPathWidth();
canvas[ 0 ].height = pathObject.getPathHeight();
drawCanvasPath( canvas[ 0 ].getContext( "2d" ), pathObject.getCanvasPath() );
}
/* Sets the canvas path styles and draws the path */
function drawCanvasPath( context, path ) {
var i = 0;
context.shadowBlur = 15;
context.shadowColor = "black";
context.strokeStyle = "white";
context.lineJoin = "round";
context.lineCap = "round";
context.lineWidth = 10;
for( ; i < path.length; i++ ) {
context[ path[ i ].method ].apply( context, path[ i ].args );
}
context.stroke();
}
/* Handles mousewheel scrolling */
function scrollHandler( e ) {
var scrollDelta = e.originalEvent.wheelDelta || -e.originalEvent.detail,
dir = scrollDelta / ( Math.abs( scrollDelta ) );
e.preventDefault();
$( window ).scrollTop( 0 ).scrollLeft( 0 );
scrollSteps( -dir * STEP_SIZE );
}
/* Handles key scrolling (arrows and space) */
function keyHandler( e ) {
// Disable scrolling with keys when user has focus on text input elements
if ( /^text/.test( e.target.type ) ) return;
switch ( e.keyCode ) {
case 40: // Down Arrow
scrollSteps( STEP_SIZE );
break;
case 38: // Up Arrow
scrollSteps( -STEP_SIZE );
break;
case 34: //Page Down
scrollSteps( BIG_STEP_SIZE );
break;
case 33: //Page Up
scrollSteps( -BIG_STEP_SIZE );
break;
case 32: // Spacebar
scrollSteps( BIG_STEP_SIZE * ( e.shiftKey ? -1 : 1 ) );
break;
case 35: // End
scrollToStep( pathList.length - 1 );
break;
case 36: //Home
scrollToStep( 0 );
break;
}
}
/* Handles scrollbar scrolling */
function dragScrollHandler( e ) {
var dragStep,
y = e.clientY - scrollBar.offset().top;
dragStep = limitWithin( Math.round( y / scrollBar.height() * ( pathList.length - 1 ) ), 0, pathList.length - 1 );
scrollToStep( snap(dragStep, STEP_SIZE) );
}
/* Scrolls forward the given amount of steps. Negative values scroll backward. */
function scrollSteps( steps ) {
scrollToStep( wrapStep( step + steps ) );
}
/* Animates forward the given amount of steps over the set duration. Negative values scroll backward */
function animateSteps ( steps, duration, easing, callback ) {
if( steps === 0 || isAnimating ) return;
if( !duration || typeof duration !== "number" ) {
if ( typeof duration === "function" ) duration();
return scrollSteps( steps );
}
isAnimating = true;
var frames = ( duration / 1000 ) * FPS,
startStep = step,
currentFrame = 0,
easedSteps,
nextStep,
interval = setInterval(function() {
easedSteps = Math.round( ($.easing[easing] || $.easing.swing)( ++currentFrame / frames, duration / frames * currentFrame, 0, steps, duration) );
nextStep = wrapStep( startStep + easedSteps);
if (currentFrame === frames) {
clearInterval( interval );
if ( typeof easing === "function" ) {
easing();
} else if ( callback ) {
callback();
}
isAnimating = false;
}
scrollToStep( nextStep, true );
}, duration / frames);
}
/* Scrolls to a specified step */
function scrollToStep( stepParam, fromAnimation ) {
if ( isAnimating && !fromAnimation ) return;
var cb;
if (pathList[ stepParam ] ){
cb = pathList[ stepParam ].callback;
element.css( makeCSS( pathList[ stepParam ] ) );
}
if( scrollHandle ) scrollHandle.css( "top", stepParam / (pathList.length - 1 ) * ( scrollBar.height() - scrollHandle.height() ) + "px" );
if ( cb && stepParam !== step && !isAnimating ) cb();
step = stepParam;
}
/* Finds the step number of a given name */
function findStep( name ) {
return pathObject.getNameMap()[ name ];
}
/* Wraps a step around the path, or limits it, depending on the wrapAround setting */
function wrapStep( wStep ) {
if ( settings.wrapAround ) {
if( isAnimating ) {
while ( wStep < 0 ) wStep += pathList.length;
while ( wStep >= pathList.length ) wStep -= pathList.length;
} else {
if ( wStep < 0 ) wStep = pathList.length - 1;
if ( wStep >= pathList.length ) wStep = 0;
}
} else {
wStep = limitWithin( wStep, 0, pathList.length - 1 );
}
return wStep;
}
/* Translates a given node in the path to CSS styles */
function makeCSS( node ) {
var centeredX = node.x - $( window ).width() / 2,
centeredY = node.y - $( window ).height() / 2,
style = {};
// Only use transforms when page is rotated
if ( normalizeAngle(node.rotate) === 0 ) {
style.left = -centeredX;
style.top = -centeredY;
applyPrefix( style, "transform-origin", "" );
applyPrefix( style, "transform", "" );
} else {
style.left = style.top = "";
applyPrefix( style, "transform-origin", node.x + "px " + node.y + "px" );
applyPrefix( style, "transform", "translate(" + -centeredX + "px, " + -centeredY + "px) rotate(" + node.rotate + "rad)" );
}
return style;
}
/* Determine the vendor prefix of the visitor's browser,
http://lea.verou.me/2009/02/find-the-vendor-prefix-of-the-current-browser/
*/
function getVendorPrefix() {
var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/,
someScript = document.getElementsByTagName( "script" )[ 0 ];
for ( var prop in someScript.style ) {
if ( regex.test(prop) ) {
return prop.match( regex )[ 0 ];
}
}
if ( "WebkitOpacity" in someScript.style ) return "Webkit";
if ( "KhtmlOpacity" in someScript.style ) return "Khtml";
return "";
}
/* Applied prefixed and unprefixed css values of a given property to a given object*/
function applyPrefix( style, prop, value ) {
style[ PREFIX + prop ] = style[ prop ] = value;
}
/* Checks for CSS transform support */
function supportsTransforms() {
var testStyle = document.createElement( "dummy" ).style,
testProps = [ "transform",
"WebkitTransform",
"MozTransform",
"OTransform",
"msTransform",
"KhtmlTransform" ],
i = 0;
for ( ; i < testProps.length; i++ ) {
if ( testStyle[testProps[ i ]] !== undefined ) {
return true;
}
}
return false;
}
/* Checks for canvas support */
function supportsCanvas() {
return !!document.createElement( "canvas" ).getContext;
}
/* Calculates the angle distance between two angles */
function sectorAngle( start, end, ccw ) {
var nStart = normalizeAngle( start ),
nEnd = normalizeAngle( end ),
diff = Math.abs( nStart - nEnd ),
invDiff = Math.PI * 2 - diff;
if ( ( ccw && nStart < nEnd ) ||
( !ccw && nStart > nEnd ) ||
( nStart === nEnd && start !== end ) // Special case *
) {
return invDiff;
}
// *: In the case of a full circle, say from 0 to 2 * Math.PI (0 to 360 degrees),
// the normalized angles would be the same, which means the sector angle is 0.
// To allow full circles, we set this special case.
return diff;
}
/* Limits a given value between a lower and upper limit */
function limitWithin( value, lowerLimit, upperLimit ) {
if ( value > upperLimit ) {
return upperLimit;
} else if ( value < lowerLimit ) {
return lowerLimit;
}
return value;
}
/* 'Snaps' a value to be a multiple of a given snap value */
function snap( value, snapValue ) {
var mod = value % snapValue;
if( mod > snapValue / 2) return value + snapValue - mod;
return value - mod;
}
/* Normalizes a given angle (sets it between 0 and 2 * Math.PI) */
function normalizeAngle( angle ) {
while( angle < 0 ) {
angle += Math.PI * 2;
}
return angle % ( Math.PI * 2 );
}
/* Calculates the hypotenuse of a right triangle with sides x and y */
function hypotenuse( x, y ) {
return Math.sqrt( x * x + y * y );
}
})( jQuery, window, document );