-
Notifications
You must be signed in to change notification settings - Fork 155
/
koala.js
324 lines (284 loc) · 9.92 KB
/
koala.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
"use strict"
/*
* Made with love by Vadim Ogievetsky for Annie Albagli (Valentine's Day 2011)
* Powered by Mike Bostock's D3
*
* For me on GitHub: https://github.com/vogievetsky/KoalasToTheMax
* License: MIT [ http://koalastothemax.com/LICENSE ]
*
* If you are reading this then I have an easter egg for you:
* You can use your own custom image as the source, simply type in:
* http://koalastothemax.com?<your image url>
* e.g.
* http://koalastothemax.com?http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Flag_of_the_United_Kingdom.svg/200px-Flag_of_the_United_Kingdom.svg.png
*
* also if you want to use a custom image and want people to guess what it is
* (without seeing the url) then you can type the url in base64 encoding like so:
* http://koalastothemax.com?<your image url in base64>
* e.g.
* http://koalastothemax.com?YXN0bGV5LmpwZw==
* (try to guess the image above)
*/
var koala = {
version: '1.8.2'
};
(function() {
function array2d(w, h) {
var a = [];
return function(x, y, v) {
if (x < 0 || y < 0) return void 0;
if (arguments.length === 3) {
// set
return a[w * x + y] = v;
} else if (arguments.length === 2) {
// get
return a[w * x + y];
} else {
throw new TypeError("Bad number of arguments");
}
}
}
// Find the color average of 4 colors in the RGB colorspace
function avgColor(x, y, z, w) {
return [
(x[0] + y[0] + z[0] + w[0]) / 4,
(x[1] + y[1] + z[1] + w[1]) / 4,
(x[2] + y[2] + z[2] + w[2]) / 4
];
}
koala.supportsCanvas = function() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
koala.supportsSVG = function() {
return !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', "svg").createSVGRect;
};
function Circle(vis, xi, yi, size, color, children, layer, onSplit) {
this.vis = vis;
this.x = size * (xi + 0.5);
this.y = size * (yi + 0.5);
this.size = size;
this.color = color;
this.rgb = d3.rgb(color[0], color[1], color[2]);
this.children = children;
this.layer = layer;
this.onSplit = onSplit;
}
Circle.prototype.isSplitable = function() {
return this.node && this.children
}
Circle.prototype.split = function() {
if (!this.isSplitable()) return;
d3.select(this.node).remove();
delete this.node;
Circle.addToVis(this.vis, this.children);
this.onSplit(this);
}
Circle.prototype.checkIntersection = function(startPoint, endPoint) {
var edx = this.x - endPoint[0],
edy = this.y - endPoint[1],
sdx = this.x - startPoint[0],
sdy = this.y - startPoint[1],
r2 = this.size / 2;
r2 = r2 * r2; // Radius squared
// End point is inside the circle and start point is outside
return edx * edx + edy * edy <= r2 && sdx * sdx + sdy * sdy > r2;
}
Circle.addToVis = function(vis, circles, init) {
var circle = vis.selectAll('.nope').data(circles)
.enter().append('circle');
if (init) {
// Setup the initial state of the initial circle
circle = circle
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', 4)
.attr('fill', '#ffffff')
.transition()
.duration(1000);
} else {
// Setup the initial state of the opened circles
circle = circle
.attr('cx', function(d) { return d.parent.x; })
.attr('cy', function(d) { return d.parent.y; })
.attr('r', function(d) { return d.parent.size / 2; })
.attr('fill', function(d) { return String(d.parent.rgb); })
.attr('fill-opacity', 0.68)
.transition()
.duration(300);
}
// Transition the to the respective final state
circle
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d) { return d.size / 2; })
.attr('fill', function(d) { return String(d.rgb); })
.attr('fill-opacity', 1)
.each('end', function(d) { d.node = this; });
}
// Main code
var vis,
maxSize = 512,
minSize = 4,
dim = maxSize / minSize;
koala.loadImage = function(imageData) {
// Create a canvas for image data resizing and extraction
var canvas = document.createElement('canvas').getContext('2d');
// Draw the image into the corner, resizing it to dim x dim
canvas.drawImage(imageData, 0, 0, dim, dim);
// Extract the pixel data from the same area of canvas
// Note: This call will throw a security exception if imageData
// was loaded from a different domain than the script.
return canvas.getImageData(0, 0, dim, dim).data;
};
koala.makeCircles = function(selector, colorData, onEvent) {
onEvent = onEvent || function() {};
var splitableByLayer = [],
splitableTotal = 0,
nextPercent = 0;
function onSplit(circle) {
// manage events
var layer = circle.layer;
splitableByLayer[layer]--;
if (splitableByLayer[layer] === 0) {
onEvent('LayerClear', layer);
}
var percent = 1 - d3.sum(splitableByLayer) / splitableTotal;
if (percent >= nextPercent) {
onEvent('PercentClear', Math.round(nextPercent * 100));
nextPercent += 0.05;
}
}
// Make sure that the SVG exists and is empty
if (!vis) {
// Create the SVG ellement
vis = d3.select(selector)
.append("svg")
.attr("width", maxSize)
.attr("height", maxSize);
} else {
vis.selectAll('circle')
.remove();
}
// Got the data now build the tree
var finestLayer = array2d(dim, dim);
var size = minSize;
// Start off by populating the base (leaf) layer
var xi, yi, t = 0, color;
for (yi = 0; yi < dim; yi++) {
for (xi = 0; xi < dim; xi++) {
color = [colorData[t], colorData[t+1], colorData[t+2]];
finestLayer(xi, yi, new Circle(vis, xi, yi, size, color));
t += 4;
}
}
// Build up successive nodes by grouping
var layer, prevLayer = finestLayer;
var c1, c2, c3, c4, currentLayer = 0;
while (size < maxSize) {
dim /= 2;
size = size * 2;
layer = array2d(dim, dim);
for (yi = 0; yi < dim; yi++) {
for (xi = 0; xi < dim; xi++) {
c1 = prevLayer(2 * xi , 2 * yi );
c2 = prevLayer(2 * xi + 1, 2 * yi );
c3 = prevLayer(2 * xi , 2 * yi + 1);
c4 = prevLayer(2 * xi + 1, 2 * yi + 1);
color = avgColor(c1.color, c2.color, c3.color, c4.color);
c1.parent = c2.parent = c3.parent = c4.parent = layer(xi, yi,
new Circle(vis, xi, yi, size, color, [c1, c2, c3, c4], currentLayer, onSplit)
);
}
}
splitableByLayer.push(dim * dim);
splitableTotal += dim * dim;
currentLayer++;
prevLayer = layer;
}
// Create the initial circle
Circle.addToVis(vis, [layer(0, 0)], true);
// Interaction helper functions
function splitableCircleAt(pos) {
var xi = Math.floor(pos[0] / minSize),
yi = Math.floor(pos[1] / minSize),
circle = finestLayer(xi, yi);
if (!circle) return null;
while (circle && !circle.isSplitable()) circle = circle.parent;
return circle || null;
}
function intervalLength(startPoint, endPoint) {
var dx = endPoint[0] - startPoint[0],
dy = endPoint[1] - startPoint[1];
return Math.sqrt(dx * dx + dy * dy);
}
function breakInterval(startPoint, endPoint, maxLength) {
var breaks = [],
length = intervalLength(startPoint, endPoint),
numSplits = Math.max(Math.ceil(length / maxLength), 1),
dx = (endPoint[0] - startPoint[0]) / numSplits,
dy = (endPoint[1] - startPoint[1]) / numSplits,
startX = startPoint[0],
startY = startPoint[1];
for (var i = 0; i <= numSplits; i++) {
breaks.push([startX + dx * i, startY + dy * i]);
}
return breaks;
}
function findAndSplit(startPoint, endPoint) {
var breaks = breakInterval(startPoint, endPoint, 4);
var circleToSplit = []
for (var i = 0; i < breaks.length - 1; i++) {
var sp = breaks[i],
ep = breaks[i+1];
var circle = splitableCircleAt(ep);
if (circle && circle.isSplitable() && circle.checkIntersection(sp, ep)) {
circle.split();
}
}
}
// Handle mouse events
var prevMousePosition = null;
function onMouseMove() {
var mousePosition = d3.mouse(vis.node());
// Do nothing if the mouse point is not valid
if (isNaN(mousePosition[0])) {
prevMousePosition = null;
return;
}
if (prevMousePosition) {
findAndSplit(prevMousePosition, mousePosition);
}
prevMousePosition = mousePosition;
d3.event.preventDefault();
}
// Handle touch events
var prevTouchPositions = {};
function onTouchMove() {
var touchPositions = d3.touches(vis.node());
for (var touchIndex = 0; touchIndex < touchPositions.length; touchIndex++) {
var touchPosition = touchPositions[touchIndex];
var prevTouchPosition = prevTouchPositions[touchPosition.identifier]
if (prevTouchPosition) {
findAndSplit(prevTouchPosition, touchPosition);
}
prevTouchPositions[touchPosition.identifier] = touchPosition;
}
d3.event.preventDefault();
}
function onTouchEnd() {
var touches = d3.event.changedTouches;
for (var touchIndex = 0; touchIndex < touches.length; touchIndex++) {
var touch = touches.item(touchIndex);
prevTouchPositions[touch.identifier] = null;
}
d3.event.preventDefault();
}
// Initialize interaction
d3.select(document.body)
.on('mousemove.koala', onMouseMove)
.on('touchmove.koala', onTouchMove)
.on('touchend.koala', onTouchEnd)
.on('touchcancel.koala', onTouchEnd);
};
})();