-
Notifications
You must be signed in to change notification settings - Fork 12
/
jcanvas.js
4382 lines (3682 loc) · 108 KB
/
jcanvas.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
/**
* @license jCanvas v21.0.1
* Copyright 2017 Caleb Evans
* Released under the MIT license
*/
(function (jQuery, global, factory) {
'use strict';
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = function (jQuery, w) {
return factory(jQuery, w);
};
} else {
factory(jQuery, global);
}
// Pass this if window is not defined yet
}(typeof window !== 'undefined' ? window.jQuery : {}, typeof window !== 'undefined' ? window : this, function ($, window) {
'use strict';
var document = window.document,
Image = window.Image,
Array = window.Array,
getComputedStyle = window.getComputedStyle,
Math = window.Math,
Number = window.Number,
parseFloat = window.parseFloat;
// Define local aliases to frequently used properties
var defaults,
// Aliases to jQuery methods
extendObject = $.extend,
inArray = $.inArray,
typeOf = function (operand) {
return Object.prototype.toString.call(operand)
.slice(8, -1).toLowerCase();
},
isPlainObject = $.isPlainObject,
// Math constants and functions
PI = Math.PI,
round = Math.round,
abs = Math.abs,
sin = Math.sin,
cos = Math.cos,
atan2 = Math.atan2,
// The Array slice() method
arraySlice = Array.prototype.slice,
// jQuery's internal event normalization function
jQueryEventFix = $.event.fix,
// Object for storing a number of internal property maps
maps = {},
// jQuery internal caches
caches = {
dataCache: {},
propCache: {},
imageCache: {}
},
// Base transformations
baseTransforms = {
rotate: 0,
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0,
// Store all previous masks
masks: []
},
// Object for storing CSS-related properties
css = {},
tangibleEvents = [
'mousedown',
'mousemove',
'mouseup',
'mouseover',
'mouseout',
'touchstart',
'touchmove',
'touchend'
];
// Constructor for creating objects that inherit from jCanvas preferences and defaults
function jCanvasObject(args) {
var params = this,
propName;
// Copy the given parameters into new object
for (propName in args) {
// Do not merge defaults into parameters
if (Object.prototype.hasOwnProperty.call(args, propName)) {
params[propName] = args[propName];
}
}
return params;
}
// jCanvas object in which global settings are other data are stored
var jCanvas = {
// Events object for storing jCanvas event initiation functions
events: {},
// Object containing all jCanvas event hooks
eventHooks: {},
// Settings for enabling future jCanvas features
future: {}
};
// jCanvas default property values
function jCanvasDefaults() {
extendObject(this, jCanvasDefaults.baseDefaults);
}
jCanvasDefaults.baseDefaults = {
align: 'center',
arrowAngle: 90,
arrowRadius: 0,
autosave: true,
baseline: 'middle',
bringToFront: false,
ccw: false,
closed: false,
compositing: 'source-over',
concavity: 0,
cornerRadius: 0,
count: 1,
cropFromCenter: true,
crossOrigin: null,
cursors: null,
disableEvents: false,
draggable: false,
dragGroups: null,
groups: null,
data: null,
dx: null,
dy: null,
end: 360,
eventX: null,
eventY: null,
fillStyle: 'transparent',
fontStyle: 'normal',
fontSize: '12pt',
fontFamily: 'sans-serif',
fromCenter: true,
height: null,
imageSmoothing: true,
inDegrees: true,
intangible: false,
index: null,
letterSpacing: null,
lineHeight: 1,
layer: false,
mask: false,
maxWidth: null,
miterLimit: 10,
name: null,
opacity: 1,
r1: null,
r2: null,
radius: 0,
repeat: 'repeat',
respectAlign: false,
restrictDragToAxis: null,
rotate: 0,
rounded: false,
scale: 1,
scaleX: 1,
scaleY: 1,
shadowBlur: 0,
shadowColor: 'transparent',
shadowStroke: false,
shadowX: 0,
shadowY: 0,
sHeight: null,
sides: 0,
source: '',
spread: 0,
start: 0,
strokeCap: 'butt',
strokeDash: null,
strokeDashOffset: 0,
strokeJoin: 'miter',
strokeStyle: 'transparent',
strokeWidth: 1,
sWidth: null,
sx: null,
sy: null,
text: '',
translate: 0,
translateX: 0,
translateY: 0,
type: null,
visible: true,
width: null,
x: 0,
y: 0
};
defaults = new jCanvasDefaults();
jCanvasObject.prototype = defaults;
/* Internal helper methods */
// Determines if the given operand is a string
function isString(operand) {
return (typeOf(operand) === 'string');
}
// Determines if the given operand is a function
function isFunction(operand) {
return (typeOf(operand) === 'function');
}
// Determines if the given operand is numeric
function isNumeric(operand) {
return !isNaN(Number(operand)) && !isNaN(parseFloat(operand));
}
// Get 2D context for the given canvas
function _getContext(canvas) {
return (canvas && canvas.getContext ? canvas.getContext('2d') : null);
}
// Coerce designated number properties from strings to numbers
function _coerceNumericProps(props) {
var propName, propType, propValue;
// Loop through all properties in given property map
for (propName in props) {
if (Object.prototype.hasOwnProperty.call(props, propName)) {
propValue = props[propName];
propType = typeOf(propValue);
// If property is non-empty string and value is numeric
if (propType === 'string' && isNumeric(propValue) && propName !== 'text') {
// Convert value to number
props[propName] = parseFloat(propValue);
}
}
}
// Ensure value of text property is always a string
if (props.text !== undefined) {
props.text = String(props.text);
}
}
// Clone the given transformations object
function _cloneTransforms(transforms) {
// Clone the object itself
transforms = extendObject({}, transforms);
// Clone the object's masks array
transforms.masks = transforms.masks.slice(0);
return transforms;
}
// Save canvas context and update transformation stack
function _saveCanvas(ctx, data) {
var transforms;
ctx.save();
transforms = _cloneTransforms(data.transforms);
data.savedTransforms.push(transforms);
}
// Restore canvas context update transformation stack
function _restoreCanvas(ctx, data) {
if (data.savedTransforms.length === 0) {
// Reset transformation state if it can't be restored any more
data.transforms = _cloneTransforms(baseTransforms);
} else {
// Restore canvas context
ctx.restore();
// Restore current transform state to the last saved state
data.transforms = data.savedTransforms.pop();
}
}
// Set the style with the given name
function _setStyle(canvas, ctx, params, styleName) {
if (params[styleName]) {
if (isFunction(params[styleName])) {
// Handle functions
ctx[styleName] = params[styleName].call(canvas, params);
} else {
// Handle string values
ctx[styleName] = params[styleName];
}
}
}
// Set canvas context properties
function _setGlobalProps(canvas, ctx, params) {
_setStyle(canvas, ctx, params, 'fillStyle');
_setStyle(canvas, ctx, params, 'strokeStyle');
ctx.lineWidth = params.strokeWidth;
// Optionally round corners for paths
if (params.rounded) {
ctx.lineCap = ctx.lineJoin = 'round';
} else {
ctx.lineCap = params.strokeCap;
ctx.lineJoin = params.strokeJoin;
ctx.miterLimit = params.miterLimit;
}
// Reset strokeDash if null
if (!params.strokeDash) {
params.strokeDash = [];
}
// Dashed lines
if (ctx.setLineDash) {
ctx.setLineDash(params.strokeDash);
}
ctx.webkitLineDash = params.strokeDash;
ctx.lineDashOffset = ctx.webkitLineDashOffset = ctx.mozDashOffset = params.strokeDashOffset;
// Drop shadow
ctx.shadowOffsetX = params.shadowX;
ctx.shadowOffsetY = params.shadowY;
ctx.shadowBlur = params.shadowBlur;
ctx.shadowColor = params.shadowColor;
// Opacity and composite operation
ctx.globalAlpha = params.opacity;
ctx.globalCompositeOperation = params.compositing;
// Support cross-browser toggling of image smoothing
if (params.imageSmoothing) {
ctx.imageSmoothingEnabled = params.imageSmoothing;
}
}
// Optionally enable masking support for this path
function _enableMasking(ctx, data, params) {
if (params.mask) {
// If jCanvas autosave is enabled
if (params.autosave) {
// Automatically save transformation state by default
_saveCanvas(ctx, data);
}
// Clip the current path
ctx.clip();
// Keep track of current masks
data.transforms.masks.push(params._args);
}
}
// Restore individual shape transformation
function _restoreTransform(ctx, params) {
// If shape has been transformed by jCanvas
if (params._transformed) {
// Restore canvas context
ctx.restore();
}
}
// Close current canvas path
function _closePath(canvas, ctx, params) {
var data;
// Optionally close path
if (params.closed) {
ctx.closePath();
}
if (params.shadowStroke && params.strokeWidth !== 0) {
// Extend the shadow to include the stroke of a drawing
// Add a stroke shadow by stroking before filling
ctx.stroke();
ctx.fill();
// Ensure the below stroking does not inherit a shadow
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
// Stroke over fill as usual
ctx.stroke();
} else {
// If shadowStroke is not enabled, stroke & fill as usual
ctx.fill();
// Prevent extra shadow created by stroke (but only when fill is present)
if (params.fillStyle !== 'transparent') {
ctx.shadowColor = 'transparent';
}
if (params.strokeWidth !== 0) {
// Only stroke if the stroke is not 0
ctx.stroke();
}
}
// Optionally close path
if (!params.closed) {
ctx.closePath();
}
// Restore individual shape transformation
_restoreTransform(ctx, params);
// Mask shape if chosen
if (params.mask) {
// Retrieve canvas data
data = _getCanvasData(canvas);
_enableMasking(ctx, data, params);
}
}
// Transform (translate, scale, or rotate) shape
function _transformShape(canvas, ctx, params, width, height) {
// Get conversion factor for radians
params._toRad = (params.inDegrees ? (PI / 180) : 1);
params._transformed = true;
ctx.save();
// Optionally measure (x, y) position from top-left corner
if (!params.fromCenter && !params._centered && width !== undefined) {
// Always draw from center unless otherwise specified
if (height === undefined) {
height = width;
}
params.x += width / 2;
params.y += height / 2;
params._centered = true;
}
// Optionally rotate shape
if (params.rotate) {
_rotateCanvas(ctx, params, null);
}
// Optionally scale shape
if (params.scale !== 1 || params.scaleX !== 1 || params.scaleY !== 1) {
_scaleCanvas(ctx, params, null);
}
// Optionally translate shape
if (params.translate || params.translateX || params.translateY) {
_translateCanvas(ctx, params, null);
}
}
/* Plugin API */
// Extend jCanvas with a user-defined method
jCanvas.extend = function extend(plugin) {
// Create plugin
if (plugin.name) {
// Merge properties with defaults
if (plugin.props) {
extendObject(defaults, plugin.props);
}
// Define plugin method
$.fn[plugin.name] = function self(args) {
var $canvases = this, canvas, e, ctx,
params;
for (e = 0; e < $canvases.length; e += 1) {
canvas = $canvases[e];
ctx = _getContext(canvas);
if (ctx) {
params = new jCanvasObject(args);
_addLayer(canvas, params, args, self);
_setGlobalProps(canvas, ctx, params);
plugin.fn.call(canvas, ctx, params);
}
}
return $canvases;
};
// Add drawing type to drawing map
if (plugin.type) {
maps.drawings[plugin.type] = plugin.name;
}
}
return $.fn[plugin.name];
};
/* Layer API */
// Retrieved the stored jCanvas data for a canvas element
function _getCanvasData(canvas) {
var dataCache = caches.dataCache, data;
if (dataCache._canvas === canvas && dataCache._data) {
// Retrieve canvas data from cache if possible
data = dataCache._data;
} else {
// Retrieve canvas data from jQuery's internal data storage
data = $.data(canvas, 'jCanvas');
if (!data) {
// Create canvas data object if it does not already exist
data = {
// The associated canvas element
canvas: canvas,
// Layers array
layers: [],
// Layer maps
layer: {
names: {},
groups: {}
},
eventHooks: {},
// All layers that intersect with the event coordinates (regardless of visibility)
intersecting: [],
// The topmost layer whose area contains the event coordinates
lastIntersected: null,
cursor: $(canvas).css('cursor'),
// Properties for the current drag event
drag: {
layer: null,
dragging: false
},
// Data for the current event
event: {
type: null,
x: null,
y: null
},
// Events which already have been bound to the canvas
events: {},
// The canvas's current transformation state
transforms: _cloneTransforms(baseTransforms),
savedTransforms: [],
// Whether a layer is being animated or not
animating: false,
// The layer currently being animated
animated: null,
// The device pixel ratio
pixelRatio: 1,
// Whether pixel ratio transformations have been applied
scaled: false,
// Whether the canvas should be redrawn when a layer mousemove
// event triggers (either directly, or indirectly via dragging)
redrawOnMousemove: false
};
// Use jQuery to store canvas data
$.data(canvas, 'jCanvas', data);
}
// Cache canvas data for faster retrieval
dataCache._canvas = canvas;
dataCache._data = data;
}
return data;
}
// Initialize all of a layer's associated jCanvas events
function _addLayerEvents($canvas, data, layer) {
var eventName;
// Determine which jCanvas events need to be bound to this layer
for (eventName in jCanvas.events) {
if (Object.prototype.hasOwnProperty.call(jCanvas.events, eventName)) {
// If layer has callback function to complement it
if (layer[eventName] || (layer.cursors && layer.cursors[eventName])) {
// Bind event to layer
_addExplicitLayerEvent($canvas, data, layer, eventName);
}
}
}
if (!data.events.mouseout) {
$canvas.bind('mouseout.jCanvas', function () {
// Retrieve the layer whose drag event was canceled
var layer = data.drag.layer, l;
// If cursor mouses out of canvas while dragging
if (layer) {
// Cancel drag
data.drag = {};
_triggerLayerEvent($canvas, data, layer, 'dragcancel');
}
// Loop through all layers
for (l = 0; l < data.layers.length; l += 1) {
layer = data.layers[l];
// If layer thinks it's still being moused over
if (layer._hovered) {
// Trigger mouseout on layer
$canvas.triggerLayerEvent(data.layers[l], 'mouseout');
}
}
// Redraw layers
$canvas.drawLayers();
});
// Indicate that an event handler has been bound
data.events.mouseout = true;
}
}
// Initialize the given event on the given layer
function _addLayerEvent($canvas, data, layer, eventName) {
// Use touch events if appropriate
// eventName = _getMouseEventName(eventName);
// Bind event to layer
jCanvas.events[eventName]($canvas, data);
layer._event = true;
}
// Add a layer event that was explicitly declared in the layer's parameter map,
// excluding events added implicitly (e.g. mousemove event required by draggable
// layers)
function _addExplicitLayerEvent($canvas, data, layer, eventName) {
_addLayerEvent($canvas, data, layer, eventName);
if (eventName === 'mouseover' || eventName === 'mouseout' || eventName === 'mousemove') {
data.redrawOnMousemove = true;
}
}
// Enable drag support for this layer
function _enableDrag($canvas, data, layer) {
var dragHelperEvents, eventName, i;
// Only make layer draggable if necessary
if (layer.draggable || layer.cursors) {
// Organize helper events which enable drag support
dragHelperEvents = ['mousedown', 'mousemove', 'mouseup'];
// Bind each helper event to the canvas
for (i = 0; i < dragHelperEvents.length; i += 1) {
// Use touch events if appropriate
eventName = dragHelperEvents[i];
// Bind event
_addLayerEvent($canvas, data, layer, eventName);
}
// Indicate that this layer has events bound to it
layer._event = true;
}
}
// Update a layer property map if property is changed
function _updateLayerName($canvas, data, layer, props) {
var nameMap = data.layer.names;
// If layer name is being added, not changed
if (!props) {
props = layer;
} else {
// Remove old layer name entry because layer name has changed
if (props.name !== undefined && isString(layer.name) && layer.name !== props.name) {
delete nameMap[layer.name];
}
}
// Add new entry to layer name map with new name
if (isString(props.name)) {
nameMap[props.name] = layer;
}
}
// Create or update the data map for the given layer and group type
function _updateLayerGroups($canvas, data, layer, props) {
var groupMap = data.layer.groups,
group, groupName, g,
index, l;
// If group name is not changing
if (!props) {
props = layer;
} else {
// Remove layer from all of its associated groups
if (props.groups !== undefined && layer.groups !== null) {
for (g = 0; g < layer.groups.length; g += 1) {
groupName = layer.groups[g];
group = groupMap[groupName];
if (group) {
// Remove layer from its old layer group entry
for (l = 0; l < group.length; l += 1) {
if (group[l] === layer) {
// Keep track of the layer's initial index
index = l;
// Remove layer once found
group.splice(l, 1);
break;
}
}
// Remove layer group entry if group is empty
if (group.length === 0) {
delete groupMap[groupName];
}
}
}
}
}
// Add layer to new group if a new group name is given
if (props.groups !== undefined && props.groups !== null) {
for (g = 0; g < props.groups.length; g += 1) {
groupName = props.groups[g];
group = groupMap[groupName];
if (!group) {
// Create new group entry if it doesn't exist
group = groupMap[groupName] = [];
group.name = groupName;
}
if (index === undefined) {
// Add layer to end of group unless otherwise stated
index = group.length;
}
// Add layer to its new layer group
group.splice(index, 0, layer);
}
}
}
// Get event hooks object for the first selected canvas
$.fn.getEventHooks = function getEventHooks() {
var $canvases = this, canvas, data,
eventHooks = {};
if ($canvases.length !== 0) {
canvas = $canvases[0];
data = _getCanvasData(canvas);
eventHooks = data.eventHooks;
}
return eventHooks;
};
// Set event hooks for the selected canvases
$.fn.setEventHooks = function setEventHooks(eventHooks) {
var $canvases = this, e,
data;
for (e = 0; e < $canvases.length; e += 1) {
data = _getCanvasData($canvases[e]);
extendObject(data.eventHooks, eventHooks);
}
return $canvases;
};
// Get jCanvas layers array
$.fn.getLayers = function getLayers(callback) {
var $canvases = this, canvas, data,
layers, layer, l,
matching = [];
if ($canvases.length !== 0) {
canvas = $canvases[0];
data = _getCanvasData(canvas);
// Retrieve layers array for this canvas
layers = data.layers;
// If a callback function is given
if (isFunction(callback)) {
// Filter the layers array using the callback
for (l = 0; l < layers.length; l += 1) {
layer = layers[l];
if (callback.call(canvas, layer)) {
// Add layer to array of matching layers if test passes
matching.push(layer);
}
}
} else {
// Otherwise, get all layers
matching = layers;
}
}
return matching;
};
// Get a single jCanvas layer object
$.fn.getLayer = function getLayer(layerId) {
var $canvases = this, canvas,
data, layers, layer, l,
idType;
if ($canvases.length !== 0) {
canvas = $canvases[0];
data = _getCanvasData(canvas);
layers = data.layers;
idType = typeOf(layerId);
if (layerId && layerId.layer) {
// Return the actual layer object if given
layer = layerId;
} else if (idType === 'number') {
// Retrieve the layer using the given index
// Allow for negative indices
if (layerId < 0) {
layerId = layers.length + layerId;
}
// Get layer with the given index
layer = layers[layerId];
} else if (idType === 'regexp') {
// Get layer with the name that matches the given regex
for (l = 0; l < layers.length; l += 1) {
// Check if layer matches name
if (isString(layers[l].name) && layers[l].name.match(layerId)) {
layer = layers[l];
break;
}
}
} else {
// Get layer with the given name
layer = data.layer.names[layerId];
}
}
return layer;
};
// Get all layers in the given group
$.fn.getLayerGroup = function getLayerGroup(groupId) {
var $canvases = this, canvas, data,
groups, groupName, group,
idType = typeOf(groupId);
if ($canvases.length !== 0) {
canvas = $canvases[0];
if (idType === 'array') {
// Return layer group if given
group = groupId;
} else if (idType === 'regexp') {
// Get canvas data
data = _getCanvasData(canvas);
groups = data.layer.groups;
// Loop through all layers groups for this canvas
for (groupName in groups) {
// Find a group whose name matches the given regex
if (groupName.match(groupId)) {
group = groups[groupName];
// Stop after finding the first matching group
break;
}
}
} else {
// Find layer group with the given group name
data = _getCanvasData(canvas);
group = data.layer.groups[groupId];
}
}
return group;
};
// Get index of layer in layers array
$.fn.getLayerIndex = function getLayerIndex(layerId) {
var $canvases = this,
layers = $canvases.getLayers(),
layer = $canvases.getLayer(layerId);
return inArray(layer, layers);
};
// Set properties of a layer
$.fn.setLayer = function setLayer(layerId, props) {
var $canvases = this, $canvas, e,
data, layer,
propName, propValue, propType;
for (e = 0; e < $canvases.length; e += 1) {
$canvas = $($canvases[e]);
data = _getCanvasData($canvases[e]);
layer = $($canvases[e]).getLayer(layerId);
if (layer) {
// Update layer property maps
_updateLayerName($canvas, data, layer, props);
_updateLayerGroups($canvas, data, layer, props);
_coerceNumericProps(props);
// Merge properties with layer
for (propName in props) {
if (Object.prototype.hasOwnProperty.call(props, propName)) {
propValue = props[propName];
propType = typeOf(propValue);
if (propType === 'object' && isPlainObject(propValue)) {
// Clone objects
layer[propName] = extendObject({}, propValue);
_coerceNumericProps(layer[propName]);
} else if (propType === 'array') {
// Clone arrays
layer[propName] = propValue.slice(0);
} else if (propType === 'string') {
if (propValue.indexOf('+=') === 0) {
// Increment numbers prefixed with +=
layer[propName] += parseFloat(propValue.substr(2));
} else if (propValue.indexOf('-=') === 0) {
// Decrement numbers prefixed with -=
layer[propName] -= parseFloat(propValue.substr(2));
} else if (!isNaN(propValue) && isNumeric(propValue) && propName !== 'text') {
// Convert numeric values as strings to numbers
layer[propName] = parseFloat(propValue);
} else {
// Otherwise, set given string value
layer[propName] = propValue;
}
} else {
// Otherwise, set given value
layer[propName] = propValue;
}
}
}
// Update layer events
_addLayerEvents($canvas, data, layer);
_enableDrag($canvas, data, layer);
// If layer's properties were changed
if ($.isEmptyObject(props) === false) {
_triggerLayerEvent($canvas, data, layer, 'change', props);
}
}
}
return $canvases;
};
// Set properties of all layers (optionally filtered by a callback)
$.fn.setLayers = function setLayers(props, callback) {
var $canvases = this, $canvas, e,
layers, l;
for (e = 0; e < $canvases.length; e += 1) {
$canvas = $($canvases[e]);
layers = $canvas.getLayers(callback);
// Loop through all layers
for (l = 0; l < layers.length; l += 1) {
// Set properties of each layer
$canvas.setLayer(layers[l], props);
}
}
return $canvases;
};
// Set properties of all layers in the given group
$.fn.setLayerGroup = function setLayerGroup(groupId, props) {
var $canvases = this, $canvas, e,
group, l;
for (e = 0; e < $canvases.length; e += 1) {
// Get layer group
$canvas = $($canvases[e]);
group = $canvas.getLayerGroup(groupId);
// If group exists
if (group) {
// Loop through layers in group
for (l = 0; l < group.length; l += 1) {
// Merge given properties with layer
$canvas.setLayer(group[l], props);
}
}
}
return $canvases;
};
// Move a layer to the given index in the layers array
$.fn.moveLayer = function moveLayer(layerId, index) {
var $canvases = this, $canvas, e,
data, layers, layer;
for (e = 0; e < $canvases.length; e += 1) {
$canvas = $($canvases[e]);
data = _getCanvasData($canvases[e]);
// Retrieve layers array and desired layer
layers = data.layers;
layer = $canvas.getLayer(layerId);
if (layer) {
// Ensure layer index is accurate
layer.index = inArray(layer, layers);
// Remove layer from its current placement
layers.splice(layer.index, 1);
// Add layer in its new placement
layers.splice(index, 0, layer);
// Handle negative indices