-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinesv2.js
653 lines (583 loc) · 18 KB
/
linesv2.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
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
644
645
646
647
648
649
650
651
652
653
/* polyfill for canvas.toBlob() from https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob */
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
len = binStr.length,
arr = new Uint8Array(len);
for (var i=0; i<len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
callback( new Blob( [arr], {type: type || 'image/png'} ) );
}
});
}
function process(img, color, hiRes) {
ds.style.display = 'none';
if(workers.length != 0) {
for(var i=0; i<workers.length; i++) {
workers[i].terminate();
}
workers = [];
}
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
if(hiRes) {
if(img.width > img.height) {
canvas.width = 1024;
canvas.height = Math.floor(img.height/img.width * 1024);
} else {
canvas.height = 1024;
canvas.width = Math.floor(img.width/img.height * 1024);
}
display.width = canvas.width/2;
display.height = canvas.height/2;
lDisplay.width = canvas.width;
lDisplay.height = canvas.height;
} else {
if(img.width > img.height) {
canvas.width = 512;
canvas.height = Math.floor(img.height/img.width * 512);
} else {
canvas.height = 512;
canvas.width = Math.floor(img.width/img.height * 512);
}
display.width = canvas.width;
display.height = canvas.height;
lDisplay.width = canvas.width*2-2;
lDisplay.height = canvas.height*2-2;
}
cWidth = canvas.width;
cHeight = canvas.height;
if(add) {
context.fillStyle = '#000000';
} else {
context.fillStyle = '#FFFFFF';
}
context.fillRect(0,0,1024,1024);
context.drawImage(img,0,0, canvas.width, canvas.height);
var imageData = context.getImageData(0,0,canvas.width, canvas.height);
var data = imageData.data;
lines = [];
linesDrawn = 0;
prepCanvas(hiRes);
if(color === false) {
totalProgress = numLines;
var gray = new Int16Array(data.length/4);
// convert to grayscale
var total = 0;
for(var i=0; i < data.length/4; i++) {
gray[i] = (Math.floor(0.21 * data[i*4] + 0.72 * data[i*4+1] + 0.07 * data[i*4+2])) // grayscale using CIE luminance
total += gray[i];
}
workers.push(new Worker('javascripts/workerv2.js'));
workers[0].addEventListener('message', drawLineMaker(0,hiRes), false);
workers[0].postMessage({add: add, lineStep: lineStep, numLines: numLines, testLines: testLines, img: gray, width: imageData.width, height: imageData.height, total: total});
} else {
var red = new Int16Array(data.length/4);
var green = new Int16Array(data.length/4);
var blue = new Int16Array(data.length/4);
var rTotal = 0;
var gTotal = 0;
var bTotal = 0;
for(var i=0; i < data.length/4; i++) {
red[i] = (data[i*4]);
green[i] = (data[i*4+1]);
blue[i] = (data[i*4+2]);
rTotal += red[i];
gTotal += green[i];
bTotal += blue[i];
}
if(!add) {
rTotal = data.length/4 * 255 - rTotal;
gTotal = data.length/4 * 255 - gTotal;
bTotal = data.length/4 * 255 - bTotal;
}
if(rTotal >= gTotal && rTotal >= bTotal) {
var rNum = numLines;
var gNum = Math.floor(numLines * gTotal/rTotal);
var bNum = Math.floor(numLines * bTotal/rTotal);
} else if(gTotal >= rTotal && gTotal >= bTotal) {
var rNum = Math.floor(numLines * rTotal/gTotal);
var gNum = numLines;
var bNum = Math.floor(numLines * bTotal/gTotal);
} else if(bTotal >= rTotal && bTotal >= gTotal) {
var rNum = Math.floor(numLines * rTotal/bTotal);
var gNum = Math.floor(numLines * gTotal/bTotal);
var bNum = numLines;
}
totalProgress = rNum + gNum + bNum;
workers.push(new Worker('javascripts/workerv2.js'));
workers[0].addEventListener('message', drawLineMaker(1,hiRes), false);
workers[0].postMessage({add: add, lineStep: lineStep, numLines: rNum, testLines: testLines, img: red, width: imageData.width, height: imageData.height});
workers.push(new Worker('javascripts/workerv2.js'));
workers[1].addEventListener('message', drawLineMaker(2,hiRes), false);
workers[1].postMessage({add: add, lineStep: lineStep, numLines: gNum, testLines: testLines, img: green, width: imageData.width, height: imageData.height});
workers.push(new Worker('javascripts/workerv2.js'));
workers[2].addEventListener('message', drawLineMaker(3,hiRes), false);
workers[2].postMessage({add: add, lineStep: lineStep, numLines: bNum, testLines: testLines, img: blue, width: imageData.width, height: imageData.height});
}
}
/* event handler for line from worker */
function drawLineMaker(color, hiRes) {
return function(e) {
linesDrawn++;
progress.style.width = linesDrawn/totalProgress * 100 + '%';
switch(color) {
case 0:
dContext.strokeStyle = 'rgba(' + lineStep + ',' + lineStep + ',' + lineStep + ',1)';
lContext.strokeStyle = 'rgba(' + lineStep + ',' + lineStep + ',' + lineStep + ',1)';
break;
case 1:
dContext.strokeStyle = 'rgba(' + lineStep + ',0,0,1)';
lContext.strokeStyle = 'rgba(' + lineStep + ',0,0,1)';
break;
case 2:
dContext.strokeStyle = 'rgba(0,' + lineStep + ',0,1)';
lContext.strokeStyle = 'rgba(0,' + lineStep + ',0,1)';
break;
case 3:
dContext.strokeStyle = 'rgba(0,0,' + lineStep + ',1)';
lContext.strokeStyle = 'rgba(0,0,' + lineStep + ',1)';
break;
}
var line = e.data;
if(hiRes) {
lineToBitsHR(color, line);
dContext.beginPath();
dContext.moveTo(line[0]/2 + 0.5, line[1]/2 + 0.5);
dContext.lineTo(line[2]/2 + 0.5, line[3]/2 + 0.5);
dContext.stroke();
lContext.beginPath();
lContext.moveTo(line[0] + 0.5, line[1] + 0.5);
lContext.lineTo(line[2] + 0.5, line[3] + 0.5);
lContext.stroke();
} else {
lineToBits(color, line);
dContext.beginPath();
dContext.moveTo(line[0] + 0.5, line[1] + 0.5);
dContext.lineTo(line[2] + 0.5, line[3] + 0.5);
dContext.stroke();
lContext.beginPath();
lContext.moveTo(line[0]*2, line[1]*2);
lContext.lineTo(line[2]*2, line[3]*2);
lContext.stroke();
}
if(linesDrawn/totalProgress == 1) {
finishedDrawing();
}
}
}
function finishedDrawing() {
var bar = document.getElementById('barBack');
bar.style.visibility = 'hidden';
lines = new Uint8Array(lines); // convert lines to Uint8Array
ds.style.display = 'block';
}
function submitFunc(e) {
e.preventDefault();
form[10].innerHTML = '<i class="fa fa-cog fa-spin"></i> Draw!'
if(form.elements[3].checked === true) {
add = 1;
} else {
add = 0;
}
numLines = parseInt(form.elements[6].value, 10);
lineStep = parseInt(form.elements[7].value, 10);
testLines = parseInt(form.elements[8].value, 10);
storeSettings();
if(fileInput.files[0] != undefined) {
image.src = URL.createObjectURL(fileInput.files[0]);
cors = true; // in case of error
} else {
image.src = form.elements[0].value;
cors = false;
}
}
function dLinkFunc(e) {
e.preventDefault();
var now = new Date();
var string = now.toISOString();
lDisplay.toBlob(function(blob) {
saveAs(blob, 'linify_' + string.slice(0,10) + '_' + string.slice(11,13) + '-' + string.slice(14,16)+ '.png');
});
}
function sLinkFunc(e) {
if(shared === false) {
sLink.innerHTML = '<i class="fa fa-cog fa-spin"></i> Save';
shared = true;
lDisplay.toBlob(function(blob) {
var formData = new FormData();
formData.append('add', add);
formData.append('lineStep', lineStep);
formData.append('width', cWidth);
formData.append('height', cHeight);
formData.append('size', blob.size);
formData.append('image', blob);
formData.append('lines', new Blob([lines], {type: 'application/octet-stream'}));
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState === XMLHttpRequest.DONE) {
if(req.status === 200) {
window.location.href = '/' + req.responseText;
} else {
shared = false;
sLink.innerHTML = '<i class="fa fa-cloud-upload></i> Save';
}
}
}
req.open('POST', '/u', true);
req.send(formData);
}, 'image/png');
}
}
function sizeFunc(e) {
display.style.display = 'none';
lDisplay.style.display = 'inline';
size.style.display = 'none';
rSize.style.display = 'inline-block';
if(typeof rLink !== 'undefined') {
prepCanvas(hiRes);
new reconstructLines(array);
}
}
function rSizeFunc(e) {
lDisplay.style.display = 'none';
display.style.display = 'inline';
rSize.style.display = 'none';
size.style.display = 'inline-block';
if(typeof rLink !== 'undefined') {
prepCanvas(hiRes);
new reconstructLines(array);
}
}
function getInspired() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState === XMLHttpRequest.DONE) {
if(req.status === 200) {
try{
var data = JSON.parse(req.responseText);
shuffle(data);
var insp = document.getElementById('insp');
for(var i=0; i < data.length; i++) {
var img = new Image();
img.src = 'http://imgur.com/' + data[i] + 't.png';
img.className = 'insp';
var a = document.createElement('a');
a.href = '/' + data[i];
a.appendChild(img);
insp.appendChild(a);
}
} catch(err) {
console.log(err);
}
}
}
}
req.open('GET', '/i', true);
req.send();
}
/* adds line to array as bits */
function lineToBits(color, line) {
var start = pointToNum(line[0], line[1]);
lines.push((color << 6) | (start >> 5));
var end = pointToNum(line[2], line[3]);
lines.push((start << 3) | (end >> 8));
lines.push(end);
}
function lineToBitsHR(color, line) {
lines.push(color);
var start = pointToNum(line[0], line[1]);
var end = pointToNum(line[2], line[3]);
lines.push(start >> 4);
lines.push((start << 4) | (end >> 8));
lines.push(end);
}
/* take Uint8Array and draw to display */
function reconstructLines(array) {
playing = true; // prevents replay button from being pressed
rafID++;
this.rafID = rafID;
this.i = 0; // static variable passed through bind
if(hiRes) {
this.rate = array.length/24000;
this.lastTime = performance.now();
if(display.style.display == 'none') {
window.requestAnimationFrame(rLineLHR.bind(this, array));
} else {
window.requestAnimationFrame(rLineHR.bind(this, array));
}
} else {
this.rate = array.length/18000; // done over 6 seconds
this.lastTime = performance.now();
if(display.style.display == 'none') {
window.requestAnimationFrame(rLineL.bind(this, array));
} else {
window.requestAnimationFrame(rLine.bind(this, array));
}
}
}
/* helper function for reconstructLines, draw line in array*/
function rLine(array, time) {
var numDraw = Math.ceil((time - this.lastTime) * this.rate);
this.lastTime = time;
for(var j=0; j < numDraw; j++) {
if(this.i < array.length/3) {
var color = array[this.i*3] >> 6;
var start = numToPoint(((array[this.i*3] << 5) | (array[this.i*3+1] >> 3)) & 2047);
var end = numToPoint(((array[this.i*3+1] << 8) | array[this.i*3+2]) & 2047);
switch(color) {
case 0:
dContext.strokeStyle = 'rgba(' + lineStep + ',' + lineStep + ',' + lineStep + ',1)';
break;
case 1:
dContext.strokeStyle = 'rgba(' + lineStep + ',0,0,1)';
break;
case 2:
dContext.strokeStyle = 'rgba(0,' + lineStep + ',0,1)';
break;
case 3:
dContext.strokeStyle = 'rgba(0,0,' + lineStep + ',1)';
break;
}
dContext.beginPath();
dContext.moveTo(start[0]+0.5, start[1]+0.5);
dContext.lineTo(end[0]+0.5, end[1]+0.5);
dContext.stroke();
this.i++;
}
}
if(this.i < array.length/3 && rafID == this.rafID) {
window.requestAnimationFrame(rLine.bind(this, array));
} else {
playing = false;
}
}
function rLineL(array, time) {
var numDraw = Math.ceil((time - this.lastTime) * this.rate);
this.lastTime = time;
for(var j=0; j < numDraw; j++) {
if(this.i < array.length/3) {
var color = array[this.i*3] >> 6;
var start = numToPoint(((array[this.i*3] << 5) | (array[this.i*3+1] >> 3)) & 2047);
var end = numToPoint(((array[this.i*3+1] << 8) | array[this.i*3+2]) & 2047);
switch(color) {
case 0:
lContext.strokeStyle = 'rgba(' + lineStep + ',' + lineStep + ',' + lineStep + ',1)';
break;
case 1:
lContext.strokeStyle = 'rgba(' + lineStep + ',0,0,1)';
break;
case 2:
lContext.strokeStyle = 'rgba(0,' + lineStep + ',0,1)';
break;
case 3:
lContext.strokeStyle = 'rgba(0,0,' + lineStep + ',1)';
break;
}
lContext.beginPath();
lContext.moveTo(start[0]*2, start[1]*2);
lContext.lineTo(end[0]*2, end[1]*2);
lContext.stroke();
this.i++;
}
}
if(this.i < array.length/3 && rafID == this.rafID) {
window.requestAnimationFrame(rLineL.bind(this, array));
} else {
playing = false;
}
}
function rLineHR(array, time) {
var numDraw = Math.ceil((time - this.lastTime) * this.rate);
this.lastTime = time;
for(var j=0; j < numDraw; j++) {
if(this.i < array.length/4) {
var color = array[this.i*4];
var start = numToPoint(((array[this.i*4+1] << 4) | (array[this.i*4+2] >> 4)) & 4095);
var end = numToPoint(((array[this.i*4+2] << 8) | array[this.i*4+3]) & 4095);
switch(color) {
case 0:
dContext.strokeStyle = 'rgba(' + lineStep + ',' + lineStep + ',' + lineStep + ',1)';
break;
case 1:
dContext.strokeStyle = 'rgba(' + lineStep + ',0,0,1)';
break;
case 2:
dContext.strokeStyle = 'rgba(0,' + lineStep + ',0,1)';
break;
case 3:
dContext.strokeStyle = 'rgba(0,0,' + lineStep + ',1)';
break;
}
dContext.beginPath();
dContext.moveTo(start[0]/2+0.5, start[1]/2+0.5);
dContext.lineTo(end[0]/2+0.5, end[1]/2+0.5);
dContext.stroke();
this.i++;
}
}
if(this.i < array.length/4 && rafID == this.rafID) {
window.requestAnimationFrame(rLineHR.bind(this, array));
} else {
playing = false;
}
}
function rLineLHR(array, time) {
var numDraw = Math.ceil((time - this.lastTime) * this.rate);
this.lastTime = time;
for(var j=0; j < numDraw; j++) {
if(this.i < array.length/4) {
var color = array[this.i*4];
var start = numToPoint(((array[this.i*4+1] << 4) | (array[this.i*4+2] >> 4)) & 4095);
var end = numToPoint(((array[this.i*4+2] << 8) | array[this.i*4+3]) & 4095);
switch(color) {
case 0:
lContext.strokeStyle = 'rgba(' + lineStep + ',' + lineStep + ',' + lineStep + ',1)';
break;
case 1:
lContext.strokeStyle = 'rgba(' + lineStep + ',0,0,1)';
break;
case 2:
lContext.strokeStyle = 'rgba(0,' + lineStep + ',0,1)';
break;
case 3:
lContext.strokeStyle = 'rgba(0,0,' + lineStep + ',1)';
break;
}
lContext.beginPath();
lContext.moveTo(start[0], start[1]);
lContext.lineTo(end[0], end[1]);
lContext.stroke();
this.i++;
}
}
if(this.i < array.length/4 && rafID == this.rafID) {
window.requestAnimationFrame(rLineLHR.bind(this, array));
} else {
playing = false;
}
}
/* wipes canvas, fills in background color */
function prepCanvas(hiRes) {
dContext.clearRect(0,0,display.width, display.height);
lContext.clearRect(0,0,lDisplay.width, lDisplay.height);
if(hiRes) {
dContext.lineWidth = 0.5;
lContext.lineWidth = 1;
} else {
dContext.lineWidth = 1;
lContext.lineWidth = 2;
}
if(add) {
dContext.fillStyle = '#000000';
dContext.fillRect(0,0,512,512);
dContext.globalCompositeOperation = 'lighter';
lContext.fillStyle = '#000000';
lContext.fillRect(0,0,1024,1024);
lContext.globalCompositeOperation = 'lighter';
} else {
dContext.fillStyle = '#FFFFFF';
dContext.fillRect(0,0,512,512);
dContext.globalCompositeOperation = 'difference';
lContext.fillStyle = '#FFFFFF';
lContext.fillRect(0,0,1024,1024);
lContext.globalCompositeOperation = 'difference';
}
}
/* tries to store color, add, numLines, lineStep, and testLines */
function storeSettings() {
try {
localStorage.setItem('lineStep', lineStep.toString());
localStorage.setItem('numLines', numLines.toString());
localStorage.setItem('testLines', testLines.toString());
localStorage.setItem('add', add.toString());
if(form.elements[2].checked === true) {
var color = '1';
} else {
var color = '0';
}
localStorage.setItem('color', color);
if(form.elements[9].checked === true) {
var hiRes = '1';
} else {
var hiRes = '0';
}
localStorage.setItem('hiRes', hiRes);
} catch(e) {
console.log(e);
return;
}
}
function getSettings() {
try {
if(localStorage.length != 0) {
document.getElementById('numLines').value = localStorage.getItem('numLines');
document.getElementById('lineStep').value = localStorage.getItem('lineStep');
document.getElementById('testLines').value = localStorage.getItem('testLines');
if(parseInt(localStorage.getItem('color'),10)) {
form.elements[2].checked = true;
} else {
form.elements[4].checked = true;
}
if(parseInt(localStorage.getItem('add'),10)) {
form.elements[3].checked = true;
} else {
form.elements[5].checked = true;
}
if(parseInt(localStorage.getItem('hiRes'),10)) {
form.elements[9].checked = true;
}
}
} catch(e) {
console.log(e);
return;
}
}
/* takes point, returns number based on clockwise border numeration */
function pointToNum(x, y) {
var width = cWidth-1;
var height = cHeight-1;
if(y == 0) {
return x;
}
if(x == width) {
return width + y;
}
if(y == height) {
return width*2 + height - x;
}
return width*2 + height*2 - y;
}
/* takes number, returns point */
function numToPoint(num) {
// width height needs fixing
var width = cWidth;
var height = cHeight;
if(num <= width) {
return [num, 0];
}
if(num <= width + height) {
return [width, num - width];
}
if(num <= width*2 + height) {
return [width*2 + height - num, height];
}
return [0, width*2 + height*2 - num];
}
/* Fisher-Yates Shuffle taken from http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array */
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}