-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.canvas-animation.js
281 lines (241 loc) · 8.15 KB
/
jquery.canvas-animation.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
(function (window, $) {
'use strict';
/**
* Stored reference to the jQuery-wrapped `window`.
* @type {Object}
*/
var $window = $(window);
var NAMESPACE = 'ca';
var setupCanvas = function ($canvas, options) {
var defaults = {
/**
* Width-to-height ratio of images. All images must adhere to this
* ratio.
* @type {Number}
*/
imageRatio: 1050 / 263,
/**
* Desired animation frames per second.
* @type {Number}
*/
frameInterval: 1000 / 30,
/**
* [images description]
* @type {Array}
*/
images: [],
/**
* Mobile breakpoint.
* @type {Number}
*/
mobileBreakpoint: 768,
tabletBreakpoint: 1024
};
/**
* Sequential images.
*
* This is used to store the actual `<img>` objects.
*
* @type {Array}
*/
var images = [];
/**
* Current image displayed.
*
* Track animation state with this by indicating which `<img>` in
* `images` is behing shown. This variable is that image's index.
*
* @todo Figure out a better way track state.
*
* @type {Number}
*/
var currentImage = 0;
/**
* Keep track of the loaded images.
* @type {Number}
*/
var loadedImageCount = 0;
/**
* Has the animation fired?
* @type {Boolean}
*/
var hasAnimated = false;
/**
* Is the screen high resolution?
* @return {Boolean}
*/
var isRetina = (function () {
if ('devicePixelRatio' in window && window.devicePixelRatio > 1) {
return true;
} else {
return false;
}
})();
/**
* Canvas's 2D drawing context.
* @type {Object}
*/
var context = $canvas.get(0).getContext('2d');
var canvasWidth, canvasHeight, animationTriggerPoint,
requestAnimationId, now, then, elapsed;
options = $.extend(defaults, options);
/**
* Get an image from a URL.
*
* This function is used primarily to attach `onload` methods to loaded
* images. This `onload` is able to react and set script state.
*
* @todo Figure out a better way to determine when images have loaded.
* State shouldn't be inside this function.
*
* @param {String} url Image's full URL
* @param {Number} index Image's index in a sequential array
* @return {Object} DOM `Image` element
*/
var getImage = function (url, index) {
var image = new Image();
image.onload = function () {
// Paint the first image
if (index === 0) {
paintImage(image);
}
loadedImageCount++;
};
image.src = url;
return image;
};
/**
* Paint an image to the canvas's context.
* @param {Object} image DOM `Image` object
* @return {undefined}
*/
var paintImage = function (image) {
if (image instanceof Image) {
try {
context.drawImage(image, 0, 0, canvasWidth, canvasWidth / options.imageRatio);
} catch (err) {
/** @todo Add better error handing. */
console.log(err);
}
}
};
/**
* Set the canvas's dimensions.
* @return {undefined}
*/
var setCanvasDimensions = function ($canvas) {
var $parent = $canvas.parent();
if (isRetina) {
canvasWidth = $parent.width() * 2;
canvasHeight = Math.ceil($parent.width() * 2 / options.imageRatio);
} else {
canvasWidth = $parent.width();
canvasHeight = Math.ceil($parent.width() / options.imageRatio);
}
$canvas.attr('width', canvasWidth);
$canvas.attr('height', canvasHeight);
};
/**
* Get the animation's vertical offset trigger point.
* @return {Number}
*/
var getAnimationTriggerPoint = function () {
var point;
if ($window.width() < options.mobileBreakpoint) {
point = $canvas.offset().top + $canvas.height() - 0.5 * $window.height();
} else if ($window.width() <= options.tabletBreakpoint) {
point = $canvas.offset().top + $canvas.height() - 0.75 * $window.height();
} else {
point = $canvas.offset().top + $canvas.height() - $window.height();
}
return point;
};
/**
* Fire the animation.
*
* @{@link http://codepen.io/matt-west/pen/bGdEC}
* @{@link http://stackoverflow.com/a/19772220}
*
* @return {undefined}
*/
var animate = function () {
requestAnimationId = requestAnimationFrame(animate);
now = Date.now();
elapsed = now - then;
if (currentImage >= images.length) {
cancelAnimationFrame(requestAnimationId);
} else if (elapsed > options.frameInterval) {
then = now - (elapsed % options.frameInterval);
currentImage++;
paintImage(images[currentImage]);
}
};
/**
* Maybe fire the animation based on the user's scroll position.
* @return {undefined}
*/
var maybeAnimate = function () {
var scrollTop = $window.scrollTop();
var t;
if (
! hasAnimated &&
loadedImageCount === images.length &&
scrollTop > animationTriggerPoint
) {
then = Date.now();
hasAnimated = true;
$window.unbind('scroll.' + NAMESPACE);
/**
* Delay animation by 500ms on non-mobile viewports.
*
* @todo Figure out a more obvious way to do this.
*/
if ($window.width() >= options.mobileBreakpoint) {
t = setTimeout(function () {
requestAnimationId = requestAnimationFrame(animate);
clearInterval(t);
}, 500);
} else {
requestAnimationId = requestAnimationFrame(animate);
}
}
};
/**
* Initialize the canvas.
* @return {undefined}
*/
return function init() {
var t;
// Set up the dimensions.
setCanvasDimensions($canvas);
animationTriggerPoint = getAnimationTriggerPoint();
// Retry the initial paint
paintImage(images[0]);
// Load the actual images
for (var i = 0; i < options.images.length; i++) {
images.push(getImage(options.images[i], i));
}
maybeAnimate();
$window.resize($.throttle(function () {
setCanvasDimensions($canvas);
animationTriggerPoint = getAnimationTriggerPoint();
if (hasAnimated) {
paintImage(images[images.length - 1]);
} else {
paintImage(images[0]);
}
}, 60));
$window.bind('scroll.' + NAMESPACE, $.throttle(maybeAnimate, 60));
};
};
$.fn.canvasAnimation = function (options) {
var $canvas = $(this);
if (
$canvas.prop('tagName') === 'CANVAS' &&
(((options).images || []).length || 0) !== 0
) {
setupCanvas($canvas, options)();
}
return this;
};
})(window, window.jQuery);