-
Notifications
You must be signed in to change notification settings - Fork 17
/
glitch-lib.js
391 lines (338 loc) · 11.6 KB
/
glitch-lib.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
/**
@license glitch.js v0.1 <http://www.github.com/sjhewitt/glitch.js>
Released under MIT License
Copyright (c) 2012 Simon Hewitt.
http://www.twitter.com/sjhewitt
*/
(function($){
/*global html2canvas */
var noop = function(){},
/**
* Set default properties on an object
* @param {Object} obj The target object
* @param {Object} defaults The default properties
* @return {Object} The target obj
*/
defaults = function(obj, defaults) {
for (var prop in defaults) {
if (obj[prop] == null)
obj[prop] = defaults[prop];
}
return obj;
},
/**
* Generates an integer between min and max
*
* @param {Number} min The lower bound
* @param {Number} max The upper bound
* @return {Number} A random number
*/
getRandInt = function(min, max) {
return (Math.floor(Math.random() * (max - min) + min));
};
/**
* Apply the glitch effect to a canvas object
*
* @param {HTMLCanvasElement} canvas The canvas (or HTMLImageElement) to apply the glitch to
* @param {number} amount The amount to glitch the canvas (default: 6)
* @return {HTMLCanvasElement} A canvas containing a glitched version
* of the original canvas
*/
var _glitch = function(canvas, amount) {
var
// cache the width and height of the canvas locally
x, y, w = canvas.width, h = canvas.height,
// _len is an iterator limit, initially storing the number of slices
// to create
i, _len = amount || 6,
// pick a random amount to offset the color channel
channelOffset = (getRandInt(-_len*2, _len*2) * w * + getRandInt(-_len, _len)) * 4,
// the maximum amount to offset a chunk of the image is a function of its width
maxOffset = _len * _len / 100 * w,
// vars for the width and height of the chunk that gets offset
chunkWidth, chunkHeight,
// create a temporary canvas to hold the image we're working on
tempCanvas = document.createElement("canvas"),
tempCtx = tempCanvas.getContext("2d"),
srcData, targetImageData, data;
// set the dimensions of the working canvas
tempCanvas.width = w;
tempCanvas.height = h;
// draw the initial image onto the working canvas
tempCtx.drawImage(canvas, 0, 0, w, h);
// store the data of the original image for use when offsetting a channel
srcData = tempCtx.getImageData(0, 0, w, h).data;
// randomly offset slices horizontally
for (i = 0; i < _len; i++) {
// pick a random y coordinate to slice at
y = getRandInt(0, h);
// pick a random height of the slice
chunkHeight = Math.min(getRandInt(1, h / 4), h - y);
// pick a random horizontal distance to offset the slice
x = getRandInt(1, maxOffset);
chunkWidth = w - x;
// draw the first chunk
tempCtx.drawImage(canvas,
0, y, chunkWidth, chunkHeight,
x, y, chunkWidth, chunkHeight);
// draw the rest
tempCtx.drawImage(canvas,
chunkWidth, y, x, chunkHeight,
0, y, x, chunkHeight);
}
// get hold of the ImageData for the working image
targetImageData = tempCtx.getImageData(0, 0, w, h);
// and get a local reference to the rgba data array
data = targetImageData.data;
// Copy a random color channel from the original image into
// the working canvas, offsetting it by a random amount
//
// ImageData arrays are a single dimension array that contains
// 4 values for each pixel.
// so, by initializing `i` to a random number between 0 and 2,
// and incrementing by 4 on each iteration, we can replace only
// a single channel in the image
for(i = getRandInt(0, 3), _len = srcData.length; i < _len; i += 4) {
data[i+channelOffset] = srcData[i];
}
// Make the image brighter by doubling the rgb values
for(i = 0; i < _len; i++) {
data[i++] *= 2;
data[i++] *= 2;
data[i++] *= 2;
}
// TODO: The above loops are the most costly in this function, iterating
// over all the pixels in the image twice.
// It maybe possible to optimize this by combining both loops into one,
// and only processing every other line, as alternate lines are replaced
// with black in the 'scan lines' block belop
// copy the tweaked ImageData back into the context
tempCtx.putImageData(targetImageData, 0, 0);
// add scan lines
tempCtx.fillStyle = "rgb(0,0,0)";
for (i = 0; i < h; i += 2) {
tempCtx.fillRect (0, i, w, 1);
}
return tempCanvas;
};
/**
* Creates a canvas containing a glitched version of the element
* @param {DOMElement} el The element to glitch
* @param {Object} options An object containing the complete callback,
* the amount to glitch the image, and any
* html2canvas options
*/
var glitch = function(el, options) {
options = defaults(options || {}, {
// the amount to glitch the image
amount: 6,
// a callback that takes the glitched canvas as its only argument
complete: noop
});
// callback for when the element has been rendered
options.onrendered = function(canvas) {
options.complete(_glitch(canvas, options.amount));
};
// render the element onto a canvas
html2canvas(el[0] ? el : [el], options);
};
/**
* Replace el with a glitched version of it
* @param {DOMElement} el The element to glitch
* @param {Object} options An object containing the options for glitch
*/
glitch.replace = function(el, options) {
options = options || {};
// store a reference to the complete callback so we can use the same
// options for the glitch function call
var _complete = options.complete;
options.complete = function(canvas) {
if($ && el instanceof $) {
el.after(canvas).detach();
} else {
// no jQuery...
el.parentNode.insertBefore(canvas, el);
el.parentNode.removeChild(el);
}
if(_complete){
_complete();
}
};
glitch(el, options);
};
/**
* Replace `el` with `newEl` by overlaying a glitched version of `el`, then
* animating it out to reveal `newEl`
*
* The animation will take into account elements of different sizes by sliding
* the container to reveal it, however it looks best if the elements to be
* transitioned between are of similar sizes
*
* @param {jQuery} el The original element that will be glitched
* @param {jQuery} newEl The element to show
* @param {Object} options An object containing the options for the animation
* and any options for html2canvas
*/
glitch.transition = function(el, newEl, options) {
// set the default options
options = defaults(options || {}, {
// the amount to glitch the image
amount: 6,
// A callback when the animation is complete
complete: noop,
// The delay after rendering the glitched element until starting the transition
delay: 300,
// The duration of the transition effect
duration: 500,
// The z-index to apply to the overlay. You might need to tweak this if
// you have things that appear above the element, or are using high
// z-indexes in your page
zIndex: 1000,
// the transition effect to use. This may be "fade" or "slide"
effect: "fade",
// The size of the top border. Set to 0 to disable, only used in slide mode
borderSize: 2,
// The color of the top border, only used in slide mode
borderColor: "green"
});
// add the new element to the dom so we can properly calculate its dimensions
newEl.insertAfter(el);
// store a reference to the complete callback so we can use the same
// options for the glitch function call
var _complete = options.complete,
// get the dimensions of the elements so we can resize the targetContainer
// to reveal all the content after the glitch transition
origHeight = el.outerHeight(true),
origWidth = el.outerWidth(true),
targetHeight = newEl.outerHeight(true),
targetWidth = newEl.outerWidth(true),
origOverflow = newEl.css("overflow");
// take the new element out of the dom again
newEl.detach();
// create a callback that will
options.complete = function(canvas){
// position the canvas absolutely within the container
var $canvas = $(canvas).css("position", "absolute"),
offset = el.offset(),
// create a container element that contains the canvas and position it
// over the element we're replacing
container = $("<div>").css({
"border-top": options.borderSize ? options.borderSize + "px solid " +
options.borderColor : "none",
position: "absolute",
left: offset.left,
top: offset.top - options.borderSize,
width: canvas.width,
height: canvas.height,
overflow: "hidden",
"z-index": options.zIndex
})
// add the canvas as a child to the container
.html(canvas)
// add the container to the dom
.appendTo("body")
// delay the animation a bit
.delay(options.delay),
targetContainer = $("<div>").css({
width: origWidth,
height: origHeight,
overflow: "hidden",
border: "none",
"box-sizing": "border-box"
})
.html(newEl),
// the default transition effect is to fade out
animation = {
opacity: 0
},
animateOptions = {
duration: options.duration,
complete: function(){
// when the animation is done:
// remove the container from the dom
container.remove();
// then animate the height of the new element back to its measured
// height and width
targetContainer.animate({
height: targetHeight,
width: targetWidth
},
{
duration: 100,
complete: function(){
// take the targetContainer element out of the dom
newEl.detach().insertAfter(targetContainer);
targetContainer.remove();
// call the complete callback
_complete();
// and clear all references
options = $canvas = container = null;
}
});
}
};
if(options.effect === "slide") {
// for the slide effect, we move move the container down
animation = {
top: offset.top + canvas.height,
height: 0
};
// and on each step of the animation, we need to offset the top so it
// remains in the same place on the screen
animateOptions.step = function(now, fx){
if(fx.prop === "top") {
$canvas.css("top", fx.start - now);
}
};
}
// apply the animation
container.animate(animation, animateOptions);
// replace the original element with the new one
// we use detatch so that the event handlers on the old
// element are retained.
targetContainer.insertAfter(el);
el.detach();
};
// create a glitched version of the start element
glitch(el, options);
};
window.glitch = glitch;
if($) {
/**
* jQuery glitch.js plugin
*
* This can be called in the following ways:
*
* Replace the element with a glitched version
* $("#el").glitch()
*
* Create a glitched canvas and pass it to a callback function
* $("#el").glitch(function(canvas){})
*
* Transition effect
* $("#el").glitch('transition', $("#newEl"), {})
*/
$.fn.glitch = function(method) {
var args = Array.prototype.splice.call(arguments, 1);
method = method || 'replace';
return this.each(function(){
if(method instanceof $) {
glitch.transition($(this), method, args[0]);
} else if(typeof method == 'function') {
// just a callback passed in
glitch($(this), {
complete: method
});
} else if(typeof method == 'object') {
// an options object passed in
glitch($(this), method);
} else if(glitch.hasOwnProperty(method)) {
// explicitly call a method
glitch[method].apply(null, [$(this)].concat(args));
} else {
$.error('Method ' + method + ' does not exist on jQuery.glitch');
}
});
};
}
})(window.jQuery);