-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
722 lines (654 loc) · 21.5 KB
/
main.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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//////
// Kinkade functionality
// Blame: Peter Richardson [email protected]
//
// export map object
map = (function () {
'use strict';
var map_start_location = [35.3470, 138.7379, 12.175]; // SF
/*** URL parsing ***/
// leaflet-style URL hash pattern:
// #[zoom],[lat],[lng]
var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');
if (url_hash.length == 3) {
map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
// convert from strings
map_start_location = map_start_location.map(Number);
}
/*** Map ***/
// init Leaflet map
var map = L.map('map', {"keyboardZoomOffset" : .05});
// init Tangram layer
var layer = Tangram.leafletLayer({
scene: 'scene.yaml',
attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | © OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>',
preUpdate: preUpdate
});
window.layer = layer;
var scene = layer.scene;
window.scene = scene;
// useful events to subscribe to
layer.scene.subscribe({
load: function (msg) {
// scene was loaded
injectAPIKey(msg.config);
}
});
function injectAPIKey(config) {
if (config.global && config.global.sdk_mapzen_api_key) {
config.global.sdk_mapzen_api_key = 'mapzen-tGBL5tg';
}
else {
for (var name in config.sources) {
var source = config.sources[name];
if (source.url.search('mapzen.com') > -1) {
source.url_params = source.url_params || {};
source.url_params.api_key = 'mapzen-tGBL5tg';
}
}
}
}
// setView expects format ([lat, long], zoom)
map.setView(map_start_location.slice(0, 3), map_start_location[2]);
// use Leaflet to update hash value in url with latlong
var hash = new L.Hash(map);
/***** Render loop *****/
window.addEventListener('load', function () {
// Scene initialized
layer.on('init', function() {
});
// add Tangram layer to Leaflet map
layer.addTo(map);
function readTextFile(file, callback, callbackArg)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var response = rawFile.responseText;
callback(response, callbackArg);
}
}
}
rawFile.send(null);
}
// load the scene file into a global variable for un-parsed export later
readTextFile('scene.yaml', setVariable, 'scenefile');
// make a separate callback to trigger when the file comes back
function setVariable(value, varname) {
window[varname] = value;
}
});
return map;
}());
// global variables
var kinkade = document.getElementById('kinkade');
var canvas = document.getElementById('kcanvas');
var ctx = canvas.getContext('2d');
var w = 10;
var drawing = false;
var undos = [];
var x = 0;
var y = 0;
var lastX;
var lastY;
var color = {r: 100, g: 100, b: 100};
var alpha = .1;
var blurring = false;
var rotating = false;
var rewinding = false;
// update hex value in color picker
function updateColorHex(val) {
resetFX();
valRGB = hexToRgb(val);
color = {r: valRGB.r, g: valRGB.g, b: valRGB.b};
document.getElementById("picker").value = val;
}
// set picker color value
function updateColorRGB(val) {
resetFX();
valRGB = val;
color = val;
setColor(RgbToHex(val))
}
// use preset div color for picker value
function swatch(div) {
val = getComputedStyle(div).backgroundColor.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
val = {r: val[1], g: val[2], b: val[3]};
updateColorRGB(val);
}
// set picker color value
function setColor(val) {
document.getElementById('picker').jscolor.fromString(val);
updateColorHex(val);
}
function updateWidth(val) {
resetFX();
w = val;
}
function updateAlpha(val) {
resetFX();
alpha = val;
}
function switchBrush(which) {
document.getElementById('brush1').className = "hitarea";
document.getElementById('brush2').className = "hitarea";
document.getElementById('brush3').className = "hitarea-fuzzy";
which.className = "hitarea-selected";
}
function switchFuzzyBrush(which) {
which.className = "hitarea-fuzzy-selected";
document.getElementById('brush1').className = "hitarea";
document.getElementById('brush2').className = "hitarea";
}
function updateScale(val) {
val = parseFloat(val);
if (typeof scene.styles.hillshade === 'undefined') return false;
scene.styles.hillshade.shaders.uniforms.u_scale = parseFloat(1/(Math.pow(2,val)-1));
scene.requestRedraw();
document.getElementById("scale").value = val;
document.getElementById("scale_slider").value = val;
}
function updateBlur(val) {
if (document.getElementById('webcam').checked) {
useWebcam(false);
}
if (!blurring) {
blurring = true;
}
if (rotating) {
resetRotate();
}
stackBlurImage( 'lastCanvas', 'kcanvas', val, false );
scene.loadTextures();
scene.requestRedraw();
}
function updateLines(val) {
scene.config.global.lines = val;
updateConfig();
}
function updateLabels(val) {
scene.config.global.labels = val;
updateConfig();
}
function updateOcean(val) {
scene.config.global.water = val;
updateConfig();
}
function updateConfig() {
scene.updateConfig();
updateScale(document.getElementById("scale").value);
}
function updateRotate(val) {
if (document.getElementById('webcam').checked) useWebcam(false);
val *= -1;
if (!rotating) {
rotating = true;
}
if (blurring) {
saveCanvas(false, rotate, val);
resetBlur();
} else {
rotate(val);
}
}
// rotate the canvas
function rotate(val) {
// get the last saved canvas
if (!rewinding && !rotating) {
lastCanvas.src = undos[undos.length - 1];
} else {
// saveCanvas();
rewinding = false;
rotating = true;
}
// transform the canvas - move so the rotate point is in the center of the image
ctx.translate(canvas.width/2, canvas.height/2);
// rotate
ctx.rotate(Math.PI/180*val);
// move back to original position
ctx.translate(-canvas.width/2, -canvas.height/2);
// draw the saved image on the transformed canvas
ctx.drawImage(lastCanvas, 0, 0);
// freeze current transform state
ctx.setTransform(1, 0, 0, 1, 0, 0);
// update map
scene.loadTextures();
scene.requestRedraw();
}
function resetFX(which) {
if (which != 'webcam' && document.getElementById('webcam').checked) {
useWebcam(false);
}
if (rotating || blurring) {
saveCanvas();
}
if (rotating) resetRotate();
if (blurring) resetBlur();
}
function resetRotate() {
if (rotating) {
saveCanvas();
rotating = false;
ctx.restore();
document.getElementById('rotate').value = 0;
}
}
// scrub levels of undo
function rewind(val) {
rewinding = true;
resetFX();
lastCanvas.src = undos[val];
lastCanvas.onload = function() {
ctx.drawImage(lastCanvas, 0, 0);
scene.loadTextures();
lastCanvas.onload = null;
};
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function componentToHex(c) {
var hex = parseInt(c).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function RgbToHex(val) {
return componentToHex(val.r) + componentToHex(val.g) + componentToHex(val.b);
}
function draw(x,y,w,r,g,b,a){
var gradient = ctx.createRadialGradient(x, y, 0, x, y, w);
gradient.addColorStop(0, 'rgba('+r+', '+g+', '+b+', '+a+')');
gradient.addColorStop(1, 'rgba('+r+', '+g+', '+b+', 0)');
ctx.beginPath();
ctx.arc(x, y, w, 0, 2 * Math.PI);
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
};
function saveCanvas(overwrite, callback) {
// save current state to undo history
canvas.toBlob(function(blob, overwrite) {
lastCanvas.src = URL.createObjectURL(blob);
if (overwrite) {
undos[undos.length] = lastCanvas.src;
if (typeof callback != 'undefined') callback;
// if (typeof callback != 'undefined') callback(arguments[arguments.length -1]);
} else {
undos.push(lastCanvas.src);
updateRewindSlider();
if (typeof callback != 'undefined') {
callback(arguments[arguments.length-1]);
}
// if (typeof callback != 'undefined') callback(arguments[arguments.length -1]);
}
});
}
function snapshot() {
if (document.getElementById("webcam").checked) {
useWebcam(false);
} else {
saveCanvas()
}
}
function resetBlur() {
if (blurring) {
blurring = false;
document.getElementById('blur').value = 0;
}
}
function updateRewindSlider() {
if (undos.length > 1) {
if (undos.length < 50) {
document.getElementById('rewind').disabled = false;
percentWidth = (100. / Math.max(undos.length - 1, 1));
percentWidth = percentWidth < 2 ? 2 + (percentWidth % 1)/2 : percentWidth;
var ticks = document.getElementById("ticks");
// clear ticks
ticks.innerHTML = "";
for (var i = 0; i < undos.length; i++) {
// make tick
var tick = document.createElement("div");
ticks.appendChild(tick);
tick.setAttribute("class", "rewindtick");
// keep ticks between 4.5% and 92.3%
var left = i * percentWidth * .878 + 4.5;
left = Math.min(left, 92.3);
// set tick position
tick.setAttribute("style", "left:"+left+"%");
}
}
document.getElementById('rewind').max = undos.length - 1;
document.getElementById('rewind').value = undos.length - 1;
}
}
function KeyPress(e) {
var evtobj = window.event? event : e;
var element = document.activeElement;
// if ctrl-z, undo
if (evtobj.which == 90 && evtobj.ctrlKey && !evtobj.shiftKey ||
evtobj.which == 90 && evtobj.metaKey && !evtobj.shiftKey ) {
rewindSlider.value -= 1;
rewind(rewindSlider.value);
// if ctrl-shift-z, redo
} else if (evtobj.which == 90 && evtobj.ctrlKey && evtobj.shiftKey ||
evtobj.which == 90 && evtobj.metaKey && evtobj.shiftKey ) {
rewindSlider.value = parseInt(rewindSlider.value) + 1;
rewind(rewindSlider.value);
// if esc and focused on scale
} else if (evtobj.which == 27 && element == document.getElementById('scale')) {
element.blur();
// if esc
} else if (evtobj.which == 27) {
hidePicker();
// listen for "h"
} else if (evtobj.which == 72 && element != document.getElementsByClassName('leaflet-pelias-input')[0]) {
// toggle UI
var display = map._controlContainer.style.display;
map._controlContainer.style.display = (display === "none") ? "block" : "none";
display = kinkade.style.display;
kinkade.style.display = (display === "none") ? "block" : "none";
document.getElementById('panes').style.display = (display === "none") ? "block" : "none";
}
}
function KeyRelease(e) {
var evtobj = window.event? event : e;
var element = document.activeElement;
// listen for "return"
if (evtobj.which == 13 && element == document.getElementById('scale')) {
element.select();
// update scale
} else if (element == document.getElementById('scale')) {
updateScale(element.value);
}
}
// fill canvas with white
function clearCanvas() {
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.fill();
}
function loadCanvas(dataurl) {
blurring = false;
rotating = false;
clearCanvas();
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0,canvas.width,canvas.height);
updateMap();
saveCanvas();
};
img.src = dataurl;
}
function updateMap(){
scene.loadTextures();
}
// Dropzone used for drag-n-drop
var myDropzone;
Dropzone.options.canvaswrapper = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, // MB
accept: function(file, done) {
return false; // prevents upload attempt
},
thumbnail: function(file, dataUrl) {
// use Dropzone's thumbnail as the canvas image
loadCanvas(dataUrl);
var img = new Image;
img.onload = function(){
drawImgToCanvas(img);
};
img.src = dataUrl;
},
thumbnailWidth: 512,
thumbnailHeight: 512,
previewTemplate: document.getElementById('preview-template').innerHTML
};
function exportCanvas() {
saveCanvas(false, function() {
window.open(
lastCanvas.src,
'_blank' // open in a new window/tab
);
});
}
function useWebcam(start) {
if (start) {
resetFX('webcam');
Webcam.set({
height: 256,
width: 358
});
Webcam.attach( '#kvideo' );
scene.updateConfig();
document.getElementById("flipspan").style.color = '#eee';
document.getElementById("snapshot").style.color = '#eee';
document.getElementById("flipwebcam").disabled = false;
document.getElementById("snapshot").disabled = false;
document.getElementById("blur").disabled = true;
document.getElementById("rotate").disabled = true;
}
else {
document.getElementById("webcam").checked = false;
saveCanvas();
Webcam.reset();
document.getElementById("flipspan").style.color = '#aaa';
document.getElementById("snapshot").style.color = '#aaa';
document.getElementById("flipwebcam").disabled = true;
document.getElementById("snapshot").disabled = true;
document.getElementById("blur").disabled = false;
document.getElementById("rotate").disabled = false;
}
}
function flipWebcam(active) {
if (active) {
canvas.style = 'transform:rotate(180deg)';
} else {
canvas.style = 'transform:rotate(0deg)';
}
}
function preUpdate (will_render) {
// Input
if (document.getElementById('webcam').checked) {
// video width = 358, canvas width = 256, difference = 51
// half canvas width + difference = 179
ctx.drawImage(document.querySelector('#kvideo > video'), -179, 0);
if (typeof scene != 'undefined') {
try {
scene.loadTextures();
} catch(e) {
console.log(e);
}
}
}
}
var video_capture = false;
var video_button = document.getElementById('recordvideo');
var video_blink = null;
// Take a video capture and save to file
function recordVideo() {
if (!video_capture) {
if (scene.startVideoCapture()) {
video_capture = true;
video_button.innerHTML = "STOP VIDEO";
video_blink = setInterval(function() {
var bgcolor = window.getComputedStyle( video_button ,null).getPropertyValue('background-color');
// flash recording button
video_button.style.backgroundColor = (bgcolor != "rgb(255, 192, 203)") ? "pink" : "white";
}, 500);
}
}
else {
return scene.stopVideoCapture().then(function(video) {
video_capture = false;
video_button.innerHTML = "RECORD VIDEO";
window.clearInterval(video_blink);
video_button.style.backgroundColor = "white";
saveAs(video.blob, 'tangram-video-' + (+new Date()) + '.webm');
});
}
};
if (typeof window.MediaRecorder == 'function') {
// disable for now
// video_button.style.display = "inline";
};
function togglePane(which, state) {
if (typeof state != 'undefined') {
document.getElementById(which).style.display = state == true? 'block' : 'none';
} else {
document.getElementById(which).style.display = document.getElementById(which).style.display != 'block' ? 'block' : 'none';
}
var panes = ["help", "locations", "examples", "scenespane"];
for (x in panes) {
if (panes[x] != which) {
document.getElementById(panes[x]).style.display = 'none';
}
}
}
// replace canvas with clicked image
function swapimg(div) {
img = div.childNodes[0];
drawImgToCanvas(img);
if (scene.config) updateMap();
saveCanvas();
}
function drawImgToCanvas(img) {
if (typeof img.src === 'undefined') return;
try {
ctx.drawImage(img,0,0,canvas.width,canvas.height);
} catch(e) {
return console.error('draw fail:', e);
}
sampleColors(canvas);
}
// sample image and put colors in swatches
function sampleColors(img) {
var colorThief = new ColorThief();
// debugger
p = colorThief.getPalette(img, 8);
if (p === null) {
return console.error("Empty spheremap");
}
swatches = document.getElementsByClassName('swatch');
p = sortColors(p);
for (var x = 0; x < p.length - 1; x++) {
swatches[x].style.backgroundColor = 'rgb('+p[x][0]+', '+p[x][1]+', '+p[x][2]+')';
}
}
// sort colors by hue
// http://runtime-era.blogspot.com/2011/11/grouping-html-hex-colors-by-hue-in.html
function sortColors(colors) {
for (var c = 0; c < colors.length; c++) {
// Get the RGB values to calculate the Hue
var r = colors[c][0];
var g = colors[c][1];
var b = colors[c][2];
// Getting the Max and Min values for Chroma
var max = Math.max.apply(Math, [r,g,b]);
var min = Math.min.apply(Math, [r,g,b]);
// Variables for HSV value of hex color
var chr = max-min;
var hue = 0;
var val = max;
var sat = 0;
if (val > 0) {
// Calculate Saturation only if Value isn't 0
sat = chr/val;
if (sat > 0) {
if (r == max) {
hue = 60*(((g-min)-(b-min))/chr);
if (hue < 0) {hue += 360;}
} else if (g == max) {
hue = 120+60*(((b-min)-(r-min))/chr);
} else if (b == max) {
hue = 240+60*(((r-min)-(g-min))/chr);
}
}
}
// Modifies existing objects by adding HSV values
colors[c].hue = hue;
colors[c].sat = sat;
colors[c].val = val;
}
// Sort by Hue
return colors.sort(function(a,b){return a.hue - b.hue;});
}
function loadSwatches() {
var img = new Image();
img.id = "pic"
img.src = document.getElementById("kcanvas").toDataURL();
sampleColors(document.getElementById("kcanvas"));
}
window.onload = function () {
if (location.hostname !== "localhost" && location.hostname !== "127.0.0.1" && location.protocol !== 'https:')
{
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
// set events
canvas.onselectstart = function(){ return false; };
canvas.onselectend = function(){ console.log('done'); };
canvas.addEventListener("mousedown", function(e){
resetFX();
if (document.getElementById("webcam").checked) useWebcam(false);
drawing = true;
lastX = e.offsetX;
lastY = e.offsetY;
draw(lastX, lastY, w, color.r, color.g, color.b, alpha);
});
canvas.addEventListener("mouseup", function(){
drawing = false;
scene.loadTextures();
saveCanvas();
loadSwatches();
});
document.getElementById("scale").addEventListener("focus", function(){
this.select();
});
// drawing function
// based on http://stackoverflow.com/a/17359298/738675
canvas.addEventListener("mousemove", function(e){
if (drawing) {
x = e.offsetX;
y = e.offsetY;
// the distance the mouse has moved since last mousemove event
var dis = Math.sqrt(Math.pow(lastX-x, 2)+Math.pow(lastY-y, 2));
// for each pixel distance, draw a circle on the line connecting the two points to get a continous line.
for (i=0;i<dis;i+=1) {
var s = i/dis;
draw(lastX*s + x*(1-s), lastY*s + y*(1-s),w,color.r,color.g,color.b, alpha);
}
lastX = x;
lastY = y;
scene.loadTextures();
};
});
// set up undo
window.lastCanvas = document.getElementById("lastCanvas");
window.prevCanvas = new Image;
prevCanvas.id = "prevCanvas";
window.rewindSlider = document.getElementById("rewind");
// initialize color picker
updateColorHex(document.getElementById("picker").value);
// select fuzzy brush
document.getElementById("brush3").click();
// watch for keys
document.onkeydown = KeyPress;
document.onkeyup = KeyRelease;
// load dropzone
window.myDropzone = new Dropzone("div#canvaswrapper", { url: "#"});
// load default image
document.getElementById("default").click();
// sample colors
loadSwatches();
// init first undo
saveCanvas();
}