forked from gopatrik/space.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
space.js
385 lines (320 loc) · 10.3 KB
/
space.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
//
// Uses Douglas Crockfords Object creation style
// In preparation for ES6.
//
(function () {
// Handles scroll events and attaches them to methods.
var ScrollController = function () {
var method;
var interval;
var repeatIntervalId;
var $window = $(window);
var lastScrollTop = 0;
var lastScrollTime;
var delayCount = 0;
// ----- public methods ------
// repeat function *func* every *interv*:nth millisecond
var repeatOnScroll = function (func, interv) {
method = func;
interval = interv;
window.onscroll = function () {
if(!repeatIntervalId){
startRepeat();
};
};
};
// ----- private methods ------
// Tick forwards, check for scroll stop and run *method*.
var update = function(){
if(repeatIntervalId){
// detect when to stop repeating
var tmpScrollTop = $window.scrollTop();
// delta stopped
if(tmpScrollTop == lastScrollTop){
// wait half a second extra to account for scroll easing
if(++delayCount >= 30){
delayCount = 0;
stopRepeat();
}
};
lastScrollTop = tmpScrollTop;
// run the method
method();
};
};
var startRepeat = function(){
repeatIntervalId = window.setInterval(update, interval);
};
var stopRepeat = function(){
window.clearInterval(repeatIntervalId);
repeatIntervalId = undefined;
};
return Object.freeze({
repeatOnScroll:repeatOnScroll,
getScrollTop: function () {
return lastScrollTop;
}
});
};
// animation controller
var SpaceController = function () {
var $window = $(window);
var windowHeight = $window.height();
var scrollControl = ScrollController();
var frames;
var currentFrame = 0;
var frameSelector = ".space-frame";
// Todo: make these modular from the <element>, e.g:
// e.g. <section class="frame depth-scale depth-opacity"></section>
var transitions = {
scaleIn: {'scale':{from:0, to:1}},
fadeIn: {'opacity':{from:0, to:1}},
scaleOut: {'scale':{from:1, to:1.5}},
fadeOut: {'opacity':{from:1, to:0}},
rotateQuarterRight: {'rotate':{from:0, to:90}},
rotateInQuarterClockwise: {'rotate':{from:-90, to:0}},
zoomOut:{
'scale': {from: 1, to: 0}
},
slideInBottom: {
'translate3d':{
from:{y:700},
to: {y:0}
}
},
slideOutDown: {
'translate3d':{
from:{y:0},
to: {y:700}
}
},
slideOutLeft: {
'translate3d':{
from:{x:0},
to: {x:-700}
}
},
slideOutRight: {
'translate3d':{
from:{x:0},
to: {x:700}
}
},
slideInRight: {
'translate3d':{
from:{x:700},
to: {x:0}
}
},
slideOutUp: {
'translate3d':{
from:{y:0},
to: {y:-700}
}
},
slideInTop: {
'translate3d':{
from:{y:-700},
to: {y:0}
}
},
slideInLeft: {
'translate3d':{
from:{x:-700},
to: {x:0}
}
},
slideBottomRight: {
'translate3d':{
from:{x:0, y:0},
to: {x:500, y:500}
}
},
rotate360: {
'rotate':{from:0, to:360}
},
rotate3dOut: {
'rotate3d':{
from:{x:0, y:0, z:0, angle:0},
to: {x:1, y:-1,z:0, angle:90}
}
}
};
var defaultTransition = {
all: [transitions.scaleOut, transitions.fadeOut],
enter: [],
exit:[]
};
// ----- public methods ------
var init = function () {
// compensate speed scrolling on touch screens
var touchScreenCompensation = (isMobile() ? 0.3 : 1);
var simulatedBodyHeight = 0;
// Set up frames
frames = $('.space-frame').map(function(index, frame){
// Duration for current frame, default is one.
// Other is read from html-element attribute data-duration
var duration = (frame.dataset.duration || 1) * touchScreenCompensation;
// simulated document height, to get a scrollbar and height
var simulatedHeight = duration * windowHeight;
var distanceTo = simulatedBodyHeight;
simulatedBodyHeight+= simulatedHeight;
// give each frame an id
var frameId = "frame-"+index;
frame.id = frameId;
// look for a custom transition to override the default one
var customTransition = frame.dataset.transition;
var customEnter = frame.dataset.enter;
var customExit = frame.dataset.exit;
if(customTransition || customEnter || customExit){
var newTransition = {all:[],enter:[],exit:[]};
var toTransition = function(arr){return arr.split(/\s+/).map(function(t){return transitions[t];})};
newTransition.all = customTransition ? toTransition(customTransition) : [];
newTransition.enter = customEnter ? toTransition(customEnter) : [];
newTransition.exit = customExit ? toTransition(customExit) : [];
return {selector:"#"+frameId, duration:simulatedHeight, distanceTo:distanceTo, transition:newTransition};
};
return {selector:"#"+frameId, duration:simulatedHeight, distanceTo:distanceTo};
});
// set fake body height
$('body').height(simulatedBodyHeight);
// show the first frame
$(frames[currentFrame].selector).show();
// initiate scroll controller with animate method
scrollControl.repeatOnScroll(animate, 1000/60);
};
// ----- private methods ------
var animate = function () {
window.requestAnimationFrame(function(){
setCurrentFrame();
animateFrame();
});
};
// compare scrolled distance with frames and select the correct one
var setCurrentFrame = function(){
var top = scrollControl.getScrollTop();
var trigger = frames[currentFrame].distanceTo;
// check if we are not in the interval of the current frame
if(top < trigger){ // prev frame
$('.space-frame').hide();
currentFrame--;
if (currentFrame < 0){currentFrame = 0};
$(frames[currentFrame].selector).show();
}else if(top > (trigger + frames[currentFrame].duration)){ // next frame
$('.space-frame').hide();
currentFrame++;
$(frames[currentFrame].selector).show();
};
};
function propValueToCssFormat (prop, val) {
switch (prop){
case "scale":
return 'scale('+val+')';
case "rotate":
return 'rotate('+val+'deg)';
case "translate3d":
return 'translate3d(' +
(val.x ? val.x+'px' : 0)+','+
(val.y ? val.y+'px' : 0)+','+
(val.z ? val.z+'px' : 0)+')';
case "rotate3d":
return 'rotate3d(' +
(val.x ? val.x : 0)+','+
(val.y ? val.y : 0)+','+
(val.z ? val.z : 0)+','+
(val.angle ? val.angle+'deg' : 0)+')';
default:
return val;
};
}
// Update css values of the current frame to their delta-value in the scroll progress
var animateFrame = function () {
var scrollInElement = (scrollControl.getScrollTop() - frames[currentFrame].distanceTo);
var props = {'transform':''};
// custom or default transition
var frameTransition = frames[currentFrame].transition || defaultTransition;
frameTransition.all.forEach(function (trans) {
for(var property in trans){
if (property == 'scale' || property == 'translate3d' || property == 'rotate' || property == 'rotate3d'){
props['transform'] += propValueToCssFormat(property, deltaValue(trans, scrollInElement, property));
}else{
props[property] = propValueToCssFormat(property, deltaValue(trans, scrollInElement, property));
};
};
});
if(scrollInElement <= (frames[currentFrame].duration / 2)){
frameTransition.enter.forEach(function (trans) {
for(var property in trans){
if (property == 'scale' || property == 'translate3d' || property == 'rotate'){
props['transform'] += propValueToCssFormat(property, deltaValue(trans, scrollInElement*2, property));
}else{
props[property] = propValueToCssFormat(property, deltaValue(trans, scrollInElement*2, property));
};
};
});
}else{
frameTransition.exit.forEach(function (trans) {
for(var property in trans){
if (property == 'scale' || property == 'translate3d' || property == 'rotate' || property == 'rotate3d'){
props['transform'] += propValueToCssFormat(property, deltaValue(trans, (scrollInElement - (frames[currentFrame].duration / 2))*2, property));
}else{
props[property] = propValueToCssFormat(property, deltaValue(trans, (scrollInElement - (frames[currentFrame].duration / 2))*2, property));
};
};
});
}
$(frames[currentFrame].selector).css(props);
};
var deltaValue = function(animation, delta, property) {
var value = animation[property];
var frameDuration = frames[currentFrame].duration;
var frameProgress = delta/frameDuration; // decimal percent
if(property == 'translate3d' || property == 'rotate3d'){
var trans = {};
for(axis in value.from){
trans[axis] = +linearEase(delta, value.from[axis], (value.to[axis]-value.from[axis]), frameDuration).toFixed(4);
};
return trans;
}else{
// compute delta value and round it to four digits to save performance.
return +linearEase(delta, value.from, (value.to-value.from), frameDuration).toFixed(4);
}
};
var linearEase = function(t, b, c, d) {
return b+c*(t/d);
};
var isMobile = function () {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};
// format
// {{key:{///transition///}}, key:{///transition///}}}
var addTransitions = function (customTrans) {
// transitions[]
for(var name in customTrans){
if(transitions[name]){
console.log("Transition name already exists!!!");
return
};
transitions[name] = customTrans[name];
};
// reinit with new transitons.. todo: fix so that we do not have to.
init();
}
// export immutable public properties
return Object.freeze({
init:init,
addTransitions: addTransitions
});
};
var initFrameCSS = function () {
var frameStyle = ".space-frame {display: none;position: fixed;width: 100vw;height: 100vh;} ";
var innerFrameStyle = ".space-frame .space-inner-frame {position: absolute;transform-style: preserve-3d;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);-moz-transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);-o-transform: translate(-50%, -50%);transform: translate(-50%, -50%);}"
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = frameStyle + innerFrameStyle;
document.getElementsByTagName('head')[0].appendChild(style);
}
initFrameCSS();
Space = SpaceController()
Space.init();
}).call(this);