-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomousCanvas.js
1638 lines (1417 loc) · 54.1 KB
/
randomousCanvas.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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Carlos Sanchez - 2017
// An enormous library full of canvas garbage
// NOTE: THIS LIBRARY REQUIRES randomous.js!
// --- CursorActionData ---
// Auxiliary object for describing generic cursor actions and data. Useful for
// unified mouse/touch systems (like CanvasPerformer)
function CursorActionData(action, x, y, zoomDelta)
{
this.action = action;
this.x = x;
this.y = y;
this.zoomDelta = zoomDelta || false;
this.onTarget = true;
this.targetElement = false;
this.time = 0; //Date.now();
this.modifiers = 0;
}
CursorActions =
{
Start : 1, End : 2, Drag : 4, Zoom : 8, Pan : 16, Interrupt : 32
};
CursorModifiers =
{
Ctrl : 1, Alt : 2
};
// --- CanvasPerformer ---
// Allows simple actions using unified touch and mouse on a canvas. Useful for
// drawing applications
function CanvasPerformer()
{
this.DragButton = 1;
this.PanButton = 2;
this.DragTouches = 1;
this.ZoomTouches = 2;
this.PanTouches = 2;
this.WheelZoom = 0.5;
this.OnAction = false;
this._canvas = false;
this._oldStyle = {};
var me = this;
var lastMAction = 0;
var lastTAction = 0;
var startZDistance = 0;
var lastZDistance = 0;
var lastTPosition = [-1,-1];
//Event for "mouse down". Creates a generic "cursor" action
this._evMD = function(e)
{
console.trace("CanvasPerformer mouse down");
var action = CursorActions.Start;
var buttons = e.buttons || EventUtilities.MouseButtonToButtons(e.button);
lastMAction = me.ButtonsToAction(buttons);
me.Perform(e, new CursorActionData(action | lastMAction, e.clientX, e.clientY), me._canvas);
};
//Event for "mouse up". Creates a generic "cursor" action
this._evMU = function(e)
{
console.trace("CanvasPerformer mouse up");
me.Perform(e, new CursorActionData(CursorActions.End | lastMAction, e.clientX, e.clientY), me._canvas);
lastMAction = 0;
};
//Event for the "wheel". Creates a generic "cursor" action
this._evMW = function(e)
{
me.Perform(e, new CursorActionData(CursorActions.Start | CursorActions.End | CursorActions.Zoom,
e.clientX, e.clientY, -Math.sign(e.deltaY) * me.WheelZoom), me._canvas);
};
//Event for both "touch start" and "touch end". Creates a generic "cursor" action
//Event for "touch start". Creates a generic "cursor" action
this._evTC = function(e)
{
console.trace("CanvasPerformer touch start/end event [" + e.touches.length + "]");
if(me.ZoomTouches !== 2) throw "Zoom must use 2 fingers!";
var extraAction = 0;
var nextAction = me.TouchesToAction(e.touches.length);
//If we enter evTC and there is a lastTAction, that means that last
//action has ended. Either we went from 1 touch to 0 or maybe 2 touches
//to 1 touch. Either way, that specific action has ended (2 touches is a
//zoom, 1 touch is a drag, etc.).
if(lastTAction)
{
if(nextAction) extraAction |= CursorActions.Interrupt;
me.Perform(e, new CursorActionData(CursorActions.End | lastTAction | extraAction,
lastTPosition[0], lastTPosition[1]), me._canvas);
}
//Move to the "next" action.
lastTAction = nextAction;
//if the user is ACTUALLY performing something (and this isn't just a 0
//touch event), THEN we're starting something here.
if(lastTAction)
{
if(lastTAction & CursorActions.Zoom)
{
startZDistance = me.PinchDistance(e.touches);
lastZDistance = 0;
}
lastTPosition = me.TouchesToXY(lastTAction, e.touches);
me.Perform(e, new CursorActionData(CursorActions.Start | lastTAction | extraAction,
lastTPosition[0], lastTPosition[1]), me._canvas);
}
};
//Event for "mouse move". Creates a generic "cursor" action.
this._evMM = function(e)
{
me.Perform(e, new CursorActionData(me.ButtonsToAction(e.buttons), e.clientX, e.clientY), me._canvas);
};
//Event for "touch move". Creates a generic "cursor" action.
this._evTM = function(e)
{
var action = me.TouchesToAction(e.touches.length);
lastTPosition = me.TouchesToXY(action, e.touches);
if(action & CursorActions.Zoom)
{
var startZoomDiff = me.PinchZoom(me.PinchDistance(e.touches), startZDistance);
me.Perform(e, new CursorActionData(action, lastTPosition[0], lastTPosition[1],
startZoomDiff - lastZDistance), me._canvas);
lastZDistance = startZoomDiff;
}
else
{
me.Perform(e, new CursorActionData(action, lastTPosition[0], lastTPosition[1]), me._canvas);
}
};
this._evPrevent = function(e) { e.preventDefault(); };
}
CanvasPerformer.prototype.GetModifiedCursorData = function(data, e)
{
if(!e) return data;
if(e.ctrlKey) data.modifiers |= CursorModifiers.Ctrl;
return data;
};
//Convert the "buttons" field of a mouse event to the appropriate action
CanvasPerformer.prototype.ButtonsToAction = function(buttons)
{
if(buttons & this.DragButton)
return CursorActions.Drag;
else if(buttons & this.PanButton)
return CursorActions.Pan;
};
//Convert the touch count to an appropriate action
CanvasPerformer.prototype.TouchesToAction = function(touches)
{
var action = 0;
if(touches === this.DragTouches)
action = action | CursorActions.Drag;
if(touches === this.ZoomTouches)
action = action | CursorActions.Zoom;
if(touches == this.PanTouches)
action = action | CursorActions.Pan;
return action;
};
//Convert a touch array into a certain XY position based on the given action.
CanvasPerformer.prototype.TouchesToXY = function(action, touchArray)
{
if(action & CursorActions.Zoom)
{
return MathUtilities.Midpoint(touchArray[0].clientX, touchArray[0].clientY,
touchArray[1].clientX, touchArray[1].clientY);
}
return [touchArray[0].clientX, touchArray[0].clientY];
};
//Figure out the distance of a pinch based on the given touches.
CanvasPerformer.prototype.PinchDistance = function(touchArray)
{
return MathUtilities.Distance(touchArray[0].clientX, touchArray[0].clientY,
touchArray[1].clientX, touchArray[1].clientY);
};
//Figure out the zoom difference (from the original) for a pinch. This is NOT
//the delta zoom between actions, just the delta zoom since the start of the
//pinch (or whatever is passed for oDistance)
CanvasPerformer.prototype.PinchZoom = function(distance, oDistance)
{
return Math.log2(distance / oDistance);
};
//System uses this function to determine if touches should be captured. Users
//can override this function to give their own rules for captured touches.
//Capturing a touch prevents scrolling.
CanvasPerformer.prototype.ShouldCapture = function(data)
{
return data.onTarget; //this._canvas && (this._canvas === document.activeElement);
};
CanvasPerformer.prototype.TouchEnabled = function(toggle)
{
if(toggle !== undefined)
{
if(toggle)
{
this._touchEnabled = true;
document.addEventListener("touchstart", this._evTC);
document.addEventListener("touchend", this._evTC);
document.addEventListener("touchcancel", this._evTC);
document.addEventListener("touchmove", this._evTM);
this._oldStyle = this._canvas.style.touchAction;
this._canvas.style.touchAction = "none";
//Stops initial tuochmove distance cutoff
this._canvas.addEventListener("touchstart", this._evPrevent);
}
else
{
this._touchEnabled = false;
document.removeEventListener("touchstart", this._evTC);
document.removeEventListener("touchend", this._evTC);
document.removeEventListener("touchcancel", this._evTC);
document.removeEventListener("touchmove", this._evTM);
this._canvas.removeEventListener("touchstart", this._evPrevent);
this._canvas.style.touchAction = this._oldStyle;
}
}
return this._touchEnabled;
};
CanvasPerformer.prototype.Attach = function(canvas)
{
if(this._canvas) throw "This CanvasPerformer is already attached to a canvas!";
this._canvas = canvas;
document.addEventListener("mousedown", this._evMD);
canvas.addEventListener("wheel", this._evMW);
canvas.addEventListener("contextmenu", this._evPrevent);
document.addEventListener("mouseup", this._evMU);
document.addEventListener("mousemove", this._evMM);
this.TouchEnabled(true);
};
CanvasPerformer.prototype.Detach = function()
{
if(!this._canvas) throw "This CanvasPerformer is is not attached to a canvas!";
document.removeEventListener("mousedown", this._evMD);
this._canvas.removeEventListener("wheel", this._evMW);
this._canvas.removeEventListener("contextmenu", this._evPrevent);
document.removeEventListener("mouseup", this._evMU);
document.removeEventListener("mousemove", this._evMM);
this.TouchEnabled(false);
this._canvas = false;
};
CanvasPerformer.prototype.SetInvert = function(horizontal, vertical, extraCanvases)
{
this.horizontalInvert = horizontal;
this.verticalInvert = vertical;
extraCanvases = extraCanvases || [];
extraCanvases.push(this._canvas);
for(var i = 0; i < extraCanvases.length; i++)
extraCanvases[i].style.transform = (horizontal ? "scalex(-1) " : "") + (vertical ? "scaley(-1) " : "");
//this._canvas.style.transform = (horizontal ? "scalex(-1) " : "") + (vertical ? "scaley(-1) " : "");
};
CanvasPerformer.prototype.Perform = function(e, cursorData, canvas)
{
var context = canvas.getContext("2d");
var clientRect = canvas.getBoundingClientRect();
var clientStyle = window.getComputedStyle(canvas);
var scalingX = canvas.clientWidth / canvas.width;
var scalingY = canvas.clientHeight / canvas.height;
//Do NOTHING if the canvas is non-existent
if(scalingX <= 0 || scalingY <= 0) return;
cursorData = this.GetModifiedCursorData(cursorData, e);
cursorData.clientX = cursorData.x;
cursorData.clientY = cursorData.y;
cursorData.x = (cursorData.x -
(clientRect.left + parseFloat(clientStyle.borderLeftWidth))) / scalingX;
cursorData.y = (cursorData.y -
(clientRect.top + parseFloat(clientStyle.borderTopWidth))) / scalingY;
if(this.horizontalInvert)
cursorData.x = canvas.width - cursorData.x;
if(this.verticalInvert)
cursorData.y = canvas.height - cursorData.y;
cursorData.targetElement = canvas;
cursorData.onTarget = (e.target === canvas || e.target.hasAttribute("data-rndcanvasallowtarget"));
cursorData.time = Date.now();
if(e && this.ShouldCapture(cursorData))
{
e.preventDefault();
}
if(this.OnAction) this.OnAction(cursorData, context);
};
// --- CanvasZoomer ---
// An extension to CanvasPerformer that tracks zoom. Position is also tracked,
// but panning is not implemented.
function CanvasZoomer()
{
CanvasPerformer.call(this);
this.x = 0; //You SHOULD be able to set these whenever you want.
this.y = 0;
this.zoom = 0; //Zoom works on powers. Negative is zoom out, positive is zoom in
this.minZoom = -5; //Lowest value for zoom. You may need to adapt this to your image
this.maxZoom = 5; //Highest zoom. Set to 0 for no zoom in ability.
this.Width = function() { return 1;}; //Inheritors or users will need to set these
this.Height = function() { return 1;};
}
CanvasZoomer.prototype = Object.create(CanvasPerformer.prototype);
CanvasZoomer.prototype.Scale = function()
{
return Math.pow(2, this.zoom);
};
//Get the size of the image for the current zoom.
CanvasZoomer.prototype.ZoomDimensions = function()
{
return [ Math.max(this.Width(),0.1) * this.Scale(), Math.max(this.Height(),0.1) * this.Scale() ];
};
//Perform a zoom for the given zoom amount (if possible)
CanvasZoomer.prototype.DoZoom = function(zoomAmount, cx, cy)
{
var newZoom = this.zoom + zoomAmount;
if(isNaN(cx)) cx = this.x;
if(isNaN(cy)) cy = this.y;
//console.log(this.x, this.y, cx, cy);
if(newZoom >= this.minZoom && newZoom <= this.maxZoom)
{
var oldDim = this.ZoomDimensions();
this.zoom = newZoom;
var newDim = this.ZoomDimensions();
//Warn: this IS the equation, no matter WHERE the positions are~!!
this.x = (newDim[0] / oldDim[0]) * (this.x - cx) + cx;
this.y = (newDim[1] / oldDim[1]) * (this.y - cy) + cy;
}
};
//Fix cursor data so the X and Y position is relative to the actual thing and
//not the given canvas. The 'actual thing' being the thing at this.x, this.y
CanvasZoomer.prototype.GetFixedCursorData = function(data)
{
data.x = (data.x - this.x) / this.Scale();
data.y = (data.y - this.y) / this.Scale();
data.onImage = data.x >= 0 && data.y >= 0 && data.x < this.Width() && data.y < this.Height();
return data;
};
// --- CanvasImageViewer ---
// Allows images to be panned/zoomed/etc in a canvas.
function CanvasImageViewer(image)
{
CanvasZoomer.call(this);
this.image = image; //User may not supply this. That's fine.
this.vx = 0; //Velocity of image. Will drift if no mouse input
this.vy = 0;
this.vDecay = 1.08; //This is division of velocity per frame
this.vStop = 0.15; //This is the speed at which the sliding will stop.
this.edgeBumper = 20;//How many pixels to leave on screen when at edge.
this.forceRefreshNextFrame = false;
//"Private" variables
this._oldX = -1;
this._oldY = -1;
this._oldZoom = this.zoom;
this._held = false;
this._lastFrame = 0;
//Event handlers (that can be removed, so they are members)
var viewer = this;
var actionStarted = false;
var lastAction;
this.OnAction = function(data, context)
{
if((data.action & CursorActions.Start) && data.onTarget)
actionStarted = true;
//Do NOT perform the initial drag action. Both dragging and panning
//can cause a direct position update.
viewer._held = actionStarted && !(data.action & (CursorActions.Start | CursorActions.End)) &&
(data.action & (CursorActions.Drag | CursorActions.Pan));
if(viewer._held)
{
viewer.UpdatePosition(1, data.x - lastAction.x, data.y - lastAction.y);
}
//Only perform actions if they have started WITHIN the canvas.
if(actionStarted)
{
if(data.action & CursorActions.Zoom)
viewer.DoZoom(data.zoomDelta, data.x, data.y);
}
if(data.action & CursorActions.End)
actionStarted = false;
lastAction = data;
};
this.ShouldCapture = function(data)
{
return data.onTarget && !(data.action & (CursorActions.Start | CursorActions.End));
//(data.action & (CursorActions.Pan | CursorActions.Move)) &&;//actionStarted;
};
this._evResize = function() {viewer.Refresh();};
}
//Inherit from CanvasPerformer
//CanvasImageViewer.prototype = Object.create(CanvasPerformer.prototype);
CanvasImageViewer.prototype = Object.create(CanvasZoomer.prototype);
//Refresh ONLY the graphics (not any values)
CanvasImageViewer.prototype.Refresh = function()
{
var ctx = this._canvas.getContext("2d");
CanvasUtilities.AutoSize(this._canvas);
var imageDim = this.ZoomDimensions();
ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
ctx.drawImage(this.image, this.x, this.y, imageDim[0], imageDim[1]);
};
//What to do each animation frame. Basically: only refresh the image if
//something changed, otherwise just keep track of changes and do the next frame.
CanvasImageViewer.prototype.DoFrame = function()
{
if(this._canvas)
{
var timePass = 60 * (performance.now() - this._lastFrame) / 1000;
this._lastFrame = performance.now();
requestAnimationFrame(this.DoFrame.bind(this));
if(this._held)
{
this.vx = this.x - this._oldX;
this.vy = this.y - this._oldY;
}
else
{
this.UpdatePosition(timePass);
}
if(this._oldX !== this.x || this._oldY !== this.y || this._oldZoom !== this.zoom ||
this.forceRefreshNextFrame)
{
this.Refresh();
}
this.forceRefreshNextFrame = false;
this._oldX = this.x;
this._oldY = this.y;
this._oldZoom = this.zoom;
}
};
//Update the position based on the given passage of time. In our case, this is
//the fraction of frames that have passed.
CanvasImageViewer.prototype.UpdatePosition = function(timePass, vx, vy)
{
if(vx === undefined) vx = this.vx;
if(vy === undefined) vy = this.vy;
this.x += vx * timePass;
this.y += vy * timePass;
var dims = this.ZoomDimensions();
dims[0] /= 2;
dims[1] /= 2;
this.x = MathUtilities.MinMax(this.x, -dims[0] + this.edgeBumper,
dims[0] + this._canvas.width - this.edgeBumper);
this.y = MathUtilities.MinMax(this.y, -dims[1] + this.edgeBumper,
dims[1] + this._canvas.height - this.edgeBumper);
var decay = this.vDecay * timePass;
this.vx = this.vx / decay;
this.vy = this.vy / decay;
//Halt the sliding if we get below the cutoff so we don't slide forever.
if(Math.sqrt(this.vy * this.vy + this.vx * this.vx) < this.vStop) { this.vy = 0; this.vx = 0; }
};
//Sets up the image viewer in the given canvas and "attaches" all our events
//and whatever to it.
CanvasImageViewer.prototype.Attach = function(canvas, image)
{
CanvasZoomer.prototype.Attach.apply(this, [canvas]);
if(image) this.image = image;
if(!this.image) throw "No image supplied!";
this.Width = function() {return this.image.width;};
this.Height = function() {return this.image.height;};
requestAnimationFrame(this.DoFrame.bind(this));
window.addEventListener("resize", this._evResize);
};
CanvasImageViewer.prototype.Detach = function()
{
CanvasZoomer.prototype.Detach.apply(this);
window.removeEventListener("resize", this._evResize);
};
// --- CanvasGenericViewer ---
// SHould PROBABLY be the other way around, for now it's a "child" of the image
// viewer. Fix this later!!
function CanvasGenericViewer()
{
CanvasImageViewer.call(this);
}
CanvasGenericViewer.prototype = Object.create(CanvasImageViewer.prototype);
CanvasGenericViewer.prototype.Attach = function(container, div)
{
if(!div) throw "No div supplied!";
this.SetDiv(div);
this._container = container;
container.style.position = "relative";
var canvas = document.createElement("canvas");
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.style.position = "absolute";
canvas.style.padding = "0";
canvas.style.margin = "0";
canvas.style.border = "none";
div.style.zIndex = "-10";
div.style.position = "absolute";
container.appendChild(canvas);
container.appendChild(div);
this.x = container.clientWidth / 2;
this.y = container.clientHeight / 2;
CanvasZoomer.prototype.Attach.apply(this, [canvas]);
this.Refresh();
requestAnimationFrame(this.DoFrame.bind(this));
window.addEventListener("resize", this._evResize);
};
CanvasGenericViewer.prototype.SetDiv = function(div)
{
var width = div.clientWidth;
var height = div.clientHeight;
this.Width = function() { return width; }
this.Height = function() { return height; }
this._div = div;
};
CanvasGenericViewer.prototype.Refresh = function()
{
//console.log(this.x, this.y);
var clientStyle = window.getComputedStyle(this._canvas);
this._canvas.width = this._canvas.clientWidth;
this._canvas.height = this._canvas.clientHeight;
this._div.style.left = this.x + "px";
this._div.style.top = this.y + "px";
this._div.style.transform = "translate(-50%, -50%) scale(" + this.Scale() + ")";
};
// --- MultiImageBlender ---
// Blends a series of images with a slider to pick which images to blend and
// how much. Useful for progressions (like controllable timelapses)
function MultiImageBlender()
{
this.blendGranularity = 16;
CanvasGenericViewer.call(this);
this._slider = false;
this._images = false;
}
MultiImageBlender.prototype = Object.create(CanvasGenericViewer.prototype);
MultiImageBlender.StyleID = HTMLUtilities.GetUniqueID("multiImageBlenderStyle");
MultiImageBlender.prototype.TrySetDefaultStyles = function()
{
if(document.getElementById(MultiImageBlender.StyleID))
return;
console.log("Setting up MultiImageBlender default styles for the first time");
var mStyle = document.createElement("style");
mStyle.appendChild(document.createTextNode(""));
mStyle.id = MultiImageBlender.StyleID;
document.head.insertBefore(mStyle, document.head.firstChild);
mStyle.sheet.insertRule(".imageBlenderLoadBar { height: 1.0rem; " +
"margin: 0; padding: 0; position: absolute; top: 0; left: 0; " +
"background-color: #4286f4}", 0);
mStyle.sheet.insertRule(".imageBlenderLoadText { font-size: 0.7rem; " +
"font-family: sans-serif; color: #CCC; padding: 0.1rem; " +
"position: absolute; top: 0; left: 0; margin: 0; display: block;}", 1);
mStyle.sheet.insertRule(".imageBlenderSlider { display: block; " +
"position: absolute; bottom: 0; left: 0; padding: 0; margin: 0; " +
"width: 100%; z-index: 10; }", 2);
mStyle.sheet.insertRule(".imageBlenderImages { position: relative; " +
"padding: 0; margin: 0; border: 0; }",3);
mStyle.sheet.insertRule(".imageBlenderImages img { position: absolute; " +
"padding: 0; margin: 0; border: 0; max-width: 100%; max-height: 100%;}",3);
};
//Attach the MultiImageBlender to the given div and fill it with relevant
//elements. NOTE: the div should have a well defined height! The elements we
//add (such as canvas, etc.) will fill the entire div.
MultiImageBlender.prototype.Attach = function(container)
{
this.TrySetDefaultStyles();
var blender = this;
this._slider = this.CreateSlider();
this._slider.addEventListener("input", function(){blender.UpdateImages();});
var imgdiv = this.CreateImageContainer();
CanvasGenericViewer.prototype.Attach.apply(this, [container, imgdiv]);
container.appendChild(this._slider);
};
//Remove the MultiImageBlender from the div it is attached to. This SHOULD
//leave it in the state it was in before attaching, but.... we'll see.
//MultiImageBlender.prototype.Detach = function()
//{
// if(!this._div)
// throw "This MultiImageBlender is not attached!";
//
// this._imageViewer.Detach();
//
// this._div.removeChild(this._canvas);
// this._div.removeChild(this._slider);
// this._div.style = "";
//
// this._div = false;
// window.removeEventListener("resize", this._evResize);
//};
//Update image data in the ImageViewer based on the slider position.
MultiImageBlender.prototype.UpdateImages = function()
{
var s = this._slider.value / this.blendGranularity;
for(var k = 0; k < this._images.length; k++)
this._images[k].style.opacity = (s - k < 2) ? MathUtilities.MinMax(s - k, 0, 1) : 0;
};
MultiImageBlender.prototype.CreateImageContainer = function()
{
var imgdiv = document.createElement("div");
imgdiv.className = "imageBlenderImages";
return imgdiv;
};
MultiImageBlender.prototype.CreateSlider = function()
{
var slider = document.createElement("input");
slider.setAttribute("type", "range");
slider.className = "imageBlenderSlider";
slider.min = this.blendGranularity;
slider.value = this.blendGranularity;
slider.max = this.blendGranularity;
return slider;
};
//Create/setup the loading bar element and return it.
MultiImageBlender.prototype.CreateLoadBar = function()
{
//this.TrySetDefaultStyles();
var progress = document.createElement("span");
progress.className = "imageBlenderLoadBar";
return progress;
};
//Create/setup the load text element and return it.
MultiImageBlender.prototype.CreateLoadText = function()
{
//this.TrySetDefaultStyles();
var loadText = document.createElement("span");
loadText.className = "imageBlenderLoadText";
return loadText;
};
//imageList is a list of string sources. This function will load them all, YO
MultiImageBlender.prototype.LoadImages = function(imageList)
{
this._images = [];
var loaded = 0;
var blender = this;
var progress = this.CreateLoadBar();
var loadText = this.CreateLoadText();
loadText.innerHTML = "Loading " + imageList.length + " images...";
blender._container.appendChild(progress);
blender._container.appendChild(loadText);
blender._slider.value = blender.blendGranularity;
blender._slider.max = imageList.length * blender.blendGranularity;
blender._div.style.width = 100;
blender._div.style.height = 100;
blender.SetDiv(blender._div);
for(var i = 0; i < imageList.length; i++)
{
var image = new Image();
image.addEventListener("load", function()
{
loaded++;
//console.log(image.naturalWidth, blender._div.style.width);
//Yes, we RESCAN all the images. Sometimes it takes a while to load...
//it's some dumb browser thing.
for(var j = 0; j < blender._images.length; j++)
{
blender._div.style.width =
Math.max(blender._images[j].naturalWidth, Number(blender._div.style.width.replace("px", "")));
blender._div.style.height =
Math.max(blender._images[j].naturalHeight, Number(blender._div.style.height.replace("px", "")));
}
blender.SetDiv(blender._div); //This should... maybe be fine while loading?
blender.UpdateImages();
progress.style.width = (blender._container.clientWidth * loaded / imageList.length) + "px";
if(loaded === imageList.length)
{
blender._container.removeChild(progress);
blender._container.removeChild(loadText);
}
});
image.src = imageList[i];
blender._div.appendChild(image);
blender._images.push(image);
}
};
// --- CanvasDrawer ---
// Allows art programs to be created easily from an existing canvas. Full
// functionality is achieved when layers and an overlay are provided.
function CanvasDrawerTool(tool, overlay, cursor)
{
this.tool = tool;
this.overlay = overlay;
this.interrupt = false;
this.cursor = cursor;
this.stationaryReportInterval = 0;
this.frameLock = 0;
this.updateUndoBuffer = 1;
}
function CanvasDrawerLayer(canvas, id)
{
this.canvas = canvas;
this.opacity = 1.0;
this.id = id || 0;
}
function CanvasDrawer()
{
CanvasPerformer.call(this);
this.buffers = [];
this.frameActions = [];
this.undoBuffer = false;
this.tools =
{
"freehand" : new CanvasDrawerTool(CanvasDrawer.FreehandTool),
"eraser" : new CanvasDrawerTool(CanvasDrawer.EraserTool),
"slow" : new CanvasDrawerTool(CanvasDrawer.SlowTool),
"spray" : new CanvasDrawerTool(CanvasDrawer.SprayTool),
"line" : new CanvasDrawerTool(CanvasDrawer.LineTool, CanvasDrawer.LineOverlay),
"square" : new CanvasDrawerTool(CanvasDrawer.SquareTool, CanvasDrawer.SquareOverlay),
"clear" : new CanvasDrawerTool(CanvasDrawer.ClearTool),
"fill" : new CanvasDrawerTool(CanvasDrawer.FillTool),
"dropper" : new CanvasDrawerTool(CanvasDrawer.DropperTool),
"mover" : new CanvasDrawerTool(CanvasDrawer.MoveTool, CanvasDrawer.MoveOverlay)
};
this.constants = {
"endInterrupt" : CursorActions.End | CursorActions.Interrupt
};
this.tools.slow.stationaryReportInterval = 1;
this.tools.spray.stationaryReportInterval = 1;
this.tools.slow.frameLock = 1;
this.tools.spray.frameLock = 1;
this.tools.dropper.updateUndoBuffer = 0;
this.tools.mover.interrupt = CanvasDrawer.MoveInterrupt;
this.overlay = false; //overlay is set with Attach. This false means nothing.
this.onlyInnerStrokes = true;
this.defaultCursor = "crosshair";
this.currentLayer = 0;
this.currentTool = "freehand";
this.color = "rgb(0,0,0)";
this.opacity = 1;
this.lineWidth = 2;
//this.cursorColor = "rgb(128,128,128)";
this.lineShape = "hardcircle";
this.lastAction = false;
this.ignoreCurrentStroke = false;
//All private stuff that's only used for our internal functions.
var me = this;
var strokeCount = 0;
var frameCount = 0;
this.StrokeCount = function() { return strokeCount; };
this.FrameCount = function() { return frameCount; };
this.OnUndoStateChange = false;
this.OnLayerChange = false;
this.OnColorChange = false;
this.OnAction = function(data, context)
{
if(me.CheckToolValidity("tool") && (data.action & CursorActions.Drag))
{
data.color = me.color;
data.lineWidth = me.lineWidth;
data.lineShape = me.lineShape;
data.opacity = me.opacity;
if(me.lineShape === "hardcircle")
data.lineFunction = CanvasUtilities.DrawSolidRoundLine;
else if(me.lineShape === "hardsquare")
data.lineFunction = CanvasUtilities.DrawSolidSquareLine;
else if(me.lineShape === "normalsquare")
data.lineFunction = CanvasUtilities.DrawNormalSquareLine;
else
data.lineFunction = CanvasUtilities.DrawNormalRoundLine;
//Replace this with some generic cursor drawing thing that takes both
//strings AND functions to draw the cursor.
if(!me.CheckToolValidity("cursor") && (data.action & CursorActions.Start))
me._canvas.style.cursor = me.defaultCursor;
if(data.action & CursorActions.Start)
{
data.oldX = data.x;
data.oldY = data.y;
data.startX = data.x;
data.startY = data.y;
strokeCount++;
}
else
{
data.oldX = me.lastAction.x;
data.oldY = me.lastAction.y;
data.startX = me.lastAction.startX;
data.startY = me.lastAction.startY;
}
//Dump all frame actions on end
if((data.action & CursorActions.End))
me.frameActions = [];
if((data.action & (CursorActions.Start | CursorActions.End)) === 0
&& me.CheckToolValidity("frameLock"))
{
me.frameActions.push({"data" : data, "context": context});
}
else
{
me.PerformDrawAction(data, context);
}
}
};
this._doFrame = function()
{
frameCount++;
//Oh look, we were detached. How nice.
if(!me._canvas) return;
//I don't care what the tool wants or what the settings are, all I care
//about is whether or not there are actions for me to perform. Maybe some
//other thing added actions; I shouldn't ignore those.
if(me.frameActions.length)
{
me.PerformDrawAction(me.frameActions[me.frameActions.length - 1].data,
me.frameActions[me.frameActions.length - 1].context);
me.frameActions = [];
}
//Only reperform the last action if there was no action this frame, both
//the tool and the reportInterval are valid, there even WAS a lastAction
//which had Drag but not Start/End, and it's far enough away from the
//last stationary report.
else if (me.CheckToolValidity("stationaryReportInterval") && me.CheckToolValidity("tool") &&
me.lastAction && (me.lastAction.action & CursorActions.Drag) &&
!(me.lastAction.action & CursorActions.End) &&
(frameCount % me.tools[me.currentTool].stationaryReportInterval) === 0)
{
me.PerformDrawAction(me.lastAction, me.GetCurrentCanvas().getContext("2d"));
}
requestAnimationFrame(me._doFrame);
};
}
//Inherit from CanvasPerformer
CanvasDrawer.prototype = Object.create(CanvasPerformer.prototype);
CanvasDrawer.prototype.Buffered = function()
{ return this.buffers.length > 0; };
//Convert layer ID (which can be anything) to actual index into layer buffer.
//Only works if there is actually a buffer.
CanvasDrawer.prototype.LayerIDToBufferIndex = function(id)
{
for(var i = 0; i < this.buffers.length; i++)
if(this.buffers[i].id === id)
return i;
return -1;
};
CanvasDrawer.prototype.CurrentLayerIndex = function()
{ return this.LayerIDToBufferIndex(this.currentLayer); };
CanvasDrawer.prototype.GetLayerByID = function(id)
{ return this.buffers[this.LayerIDToBufferIndex(id)]; };
//Only works if it's buffered. Otherwise, you'll actually get an error.
CanvasDrawer.prototype.GetCurrentLayer= function()
{ return this.GetLayerByID(this.currentLayer); };
//Get the canvas that the user should currently be drawing on.
CanvasDrawer.prototype.GetCurrentCanvas = function()
{
if(this.Buffered())
return this.GetCurrentLayer().canvas;
else
return this._canvas;
};
CanvasDrawer.prototype.ClearLayer = function(layer)
{
this.UpdateUndoBuffer();
if(layer !== undefined && this.Buffered())
CanvasUtilities.Clear(this.GetLayerByID(layer).canvas, false);
else
CanvasUtilities.Clear(this.GetCurrentCanvas(), false);
this.Redraw();
};
CanvasDrawer.prototype.CheckToolValidity = function(field)
{
return this.tools && this.tools[this.currentTool] &&
(!field || this.tools[this.currentTool][field]);
};
CanvasDrawer.prototype.SupportsUndo = function()
{ return (this.undoBuffer ? true : false); };
CanvasDrawer.prototype.CanUndo = function()
{ return this.SupportsUndo() && this.undoBuffer.UndoCount() > 0; };
CanvasDrawer.prototype.CanRedo = function()
{ return this.SupportsUndo() && this.undoBuffer.RedoCount() > 0; };