-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSYG-utils.js
More file actions
2782 lines (2029 loc) · 98.1 KB
/
JSYG-utils.js
File metadata and controls
2782 lines (2029 loc) · 98.1 KB
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
/*jshint forin:false, eqnull:true*/
/* globals JSYG,$,Promise*/
(function(root,factory) {
if (typeof module == "object" && typeof module.exports == "object" ) {
module.exports = factory(
require("jsyg-wrapper"),
require("jsyg-matrix"),
require("jsyg-vect"),
require("jsyg-point"),
require("jsyg-strutils")
);
}
else if (typeof define == "function" && define.amd) {
define("jsyg-utils",[
"jsyg-wrapper",
"jsyg-matrix",
"jsyg-vect",
"jsyg-point",
"jsyg-strutils"
],factory);
}
else if (root.JSYG) {
if (JSYG.Matrix && JSYG.Vect && JSYG.Point && JSYG.utf8encode) factory(JSYG,JSYG.Matrix,JSYG.Vect,JSYG.Point,JSYG);
else throw new Error("Missing dependency");
}
else throw new Error("JSYG is needed");
})(this,function(JSYG,Matrix,Vect,Point,strUtils) {
"use strict";
var svg = JSYG.support.svg;
function isWindow(obj) {
return obj != null && obj === obj.window;
}
/**
* récupère ou fixe la valeur d'un attribut (au sens xml) dans un espace de noms donné.<br/><br/>
* Pour définir rapidement plusieurs attributs, on peut passer en paramêtre un objet dont les clés sont les noms des attributs et les valeurs les valeurs à affecter.<br/> <br/>
* @param ns espace de nom.
* @param attr nom de l'attribut.
* @param val si définie, fixe la valeur de l'attribut.
* <br/><br/>
* @example :<ul>
* <li><strong>jsynObjet.attrNS('http://www.w3.org/2000/svg','name')</strong> : renvoie l'attribut name de l'élément.</li>
* <li><strong>jsynObjet.attr('name','toto')</strong> : définit l'attribut name de l'élément.</li>
* </ul>
* @returns {String,JSYG} valeur de l'attribut si val est indéfini, l'objet JSYG lui même si la méthode est appelée pour définir des valeurs.
*/
JSYG.prototype.attrNS = function(ns,attr,val) {
if (ns == null || attr == null) return this;
if (typeof(attr) == 'object') {
for (var n in attr) this.attrNS(ns,n,attr[n]);
return this;
}
if (val == null) return this[0].getAttributeNS(ns,attr);
else {
this.each(function() { this.setAttributeNS(ns,attr,val); });
}
return this;
};
/**
* Suppression d'un ou plusieurs attributs des éléments de la collection dans un espace de noms donné.
* @param ns espace de nom.
* @param attr nom de l'attribut. Le nombre d'arguments n'est pas limité.
* @returns {JSYG}
*/
JSYG.prototype.removeAttrNS = function(ns,attr) {
var a=arguments,
i,N=a.length;
this.each(function() {
for (i=1;i<N;i++) this.removeAttributeNS(ns,a[i]);
});
return this;
};
/**
* Récupère ou définit le lien de l'élément DOM. Cette méthode est utile pour harmoniser le html et le svg.
* Cette méthode permet de ce fait de définir l'attribut src des balises img.
* @param val si défini, fixe la valeur du lien.
* @returns {String,JSYG} valeur du lien si val est indéfini, l'objet JSYG lui-même sinon.
*/
JSYG.prototype.href = function(val) {
var srcTags = ['img','iframe','video','audio'],
tag = this.getTag(),
attr = (!this.isSVG() && srcTags.indexOf(tag) != -1) ? "src" : "href";
return arguments.length >= 1 ? this.attr(attr,val) : this.attr(attr);
};
/**
* Calcule la distance entre deux points
* @param pt1 Point ou objet quelconque avec les propriétés x et y
* @param pt2 Point ou objet quelconque avec les propriétés x et y
* @return {Number} distance en pixels (non arrondi)
*/
JSYG.distance = function(pt1,pt2) {
return Math.sqrt( Math.pow(pt1.x-pt2.x,2) + Math.pow(pt1.y-pt2.y,2) );
};
/**
* Renvoie un nombre borné aux limites spécifiées
* @param nb nombre
* @param min limite inférieure
* @param max limite supérieure
* @returns {Number}
* @example
* JSYG.clip(5,0,10) === 5;
* JSYG.clip(50,0,10) === 10;
* JSYG.clip(-50,0,10) === 0;
*/
JSYG.clip = function(nb,min,max) {
return nb < min ? min : (nb > max ? max : nb);
};
/**
* Execute une fonction sur le noeud et récursivement sur tous les descendants (nodeType==1 uniquement)
* @param fct le mot clé this fait référence au noeud courant. Si la fonction renvoie false, on sort de la boucle
* @param node noeud parent
*/
JSYG.walkTheDom = function(fct,node) {
if (fct.call(node) === false) return false;
node = node.firstChild;
while (node) {
if (node.nodeType == 1) {
if (JSYG.walkTheDom(fct,node) === false) return false;
}
node = node.nextSibling;
}
};
/**
* exécute une fonction sur la collection et récursivement sur tous les descendants
* @param fct le mot clé this fait référence au noeud courant. Si la fonction renvoie false, on sort de la boucle
* @returns {JSYG}
*/
JSYG.prototype.walkTheDom = function(fct) {
this.each(function() { return JSYG.walkTheDom(fct,this); });
return this;
};
/**
* Teste si le premier élément de la collection est enfant de l'élément passé en argument
* @param arg argument JSYG
* @returns {Boolean}
*/
JSYG.prototype.isChildOf = function(arg) {
var node = new JSYG(arg)[0],
parent = this[0].parentNode;
while (parent) {
if (parent === node) return true;
parent = parent.parentNode;
}
return false;
};
/**
* récupère les coordonnées du centre de l'élément.
* @param arg optionnel, 'screen','page' ou élément référent (voir JSYG.prototype.getDim pour les détails)
* @returns {Vect}
* @see JSYG.prototype.getDim
*/
JSYG.prototype.getCenter = function(arg) {
var rect = this.getDim(arg);
return new Vect(rect.x+rect.width/2,rect.y+rect.height/2);
};
/**
* définit les coordonnées du centre de l'élément par rapport au parent positionné, avant transformation.
* On peut aussi passer en argument un objet contenant les propriétés x et y.
* Il est possible de ne passer qu'une valeur sur les deux (ou null) pour centrer horizontalement ou verticalement uniquement.
* @param x abcisse
* @param y ordonnée
* @returns {JSYG}
*/
JSYG.prototype.setCenter = function(x,y) {
if (x!=null && typeof x === 'object' && y == null) {
y = x.y;
x = x.x;
}
this.each(function() {
var $this = new JSYG(this),
rect = $this.getDim(),
dim = {};
if (x!=null) dim.x = x - rect.width/2;
if (y!=null) dim.y = y - rect.height/2;
$this.setDim(dim);
});
return this;
};
/**
* récupère ou fixe les attributs de la viewBox d'un élément SVG (qui dispose de cet attribut, essentiellement les balise <svg>)
* @param dim optionnel, objet, si défini fixe les attributs
* @returns {JSYG} si dim est défini, objet avec propriétés x,y,width,height
*/
JSYG.prototype.viewBox = function(dim) {
var viewBoxElmts = ["svg","symbol","image","marker","pattern","view"],
val;
this.each(function() {
if (viewBoxElmts.indexOf(this.tagName) == -1) throw new Error(this.tagName+" is not a valid element.");
var viewBoxInit = this.viewBox.baseVal,
viewBox = viewBoxInit || {},
$this = new JSYG(this);
if (dim == null) {
val = {
x : viewBox.x || 0,
y : viewBox.y || 0,
width : viewBox.width || parseFloat($this.css('width')),
height : viewBox.height || parseFloat($this.css('height'))
};
return false;
}
else {
for (var n in dim) {
if (["x","y","width","height"].indexOf(n)!=-1) viewBox[n] = dim[n];
}
}
if (!viewBoxInit) this.setAttribute('viewBox', viewBox.x+" "+viewBox.y+" "+viewBox.width+" "+viewBox.height);
});
return val ? val : this;
};
/**
* Style par défaut des éléments html
*/
var defaultStyles = {};
/**
* Renvoie les propriétés de style par défaut du 1er élément de la collection
* @returns {Object}
*/
JSYG.prototype.getDefaultStyle = function() {
var tag = this.getTag(),
elmt,style,i,N,prop;
if (tag == 'a' && this.isSVG()) tag = 'svg:a';
if (!defaultStyles[tag]) {
defaultStyles[tag] = {};
elmt = new JSYG('<'+tag+'>');
style = getComputedStyle(elmt[0]);
for (i=0,N=style.length;i<N;i++) {
prop = style.item(i);
defaultStyles[tag][prop] = style.getPropertyValue(prop);
}
}
return defaultStyles[tag];
};
/**
* Ajoute tous les éléments de style possiblement définis en css comme attributs.<br/>
* Cela est utile en cas d'export SVG, afin d'avoir le style dans les balises et non dans un fichier à part.<br/>
* @param recursive si true applique la méthode à tous les enfants.
* @returns {JSYG}
*/
JSYG.prototype.style2attr = function(recursive) {
var href = window.location.href.replace('#'+window.location.hash,'');
function fct() {
var jThis = new JSYG(this),
isSVG = jThis.isSVG();
if (isSVG && JSYG.svgGraphics.indexOf(this.tagName) == -1) return;
var style = getComputedStyle(this),
defaultStyle = jThis.getDefaultStyle(),
styleAttr = '',
name,value,
i=0,N=style.length;
for (;i<N;i++) {
name = style.item(i);
if (isSVG && JSYG.svgCssProperties.indexOf(name)===-1) continue;
value = style.getPropertyValue(name);
if (defaultStyle[name] != value) {
//la fonction getPropertyValue renvoie url("http://monsite.fr/toto/#anchor") au lieu de url(#anchor)
if (value.indexOf(href) != -1) value = value.replace(href,'').replace(/"|'/g,'');
if (isSVG) this.setAttribute(name,value);
else styleAttr+= name+':'+value+';';
}
}
if (!isSVG) this.setAttribute('style',styleAttr);
else if (style.length) this.removeAttribute("style");
}
if (recursive) this.walkTheDom(fct);
else fct.call(this[0]);
return this;
};
/**
* Ajoute une règle de style css
* @param str chaîne css
* @example
* JSYG.addStyle(".maClass { font-style:italic }");
*/
JSYG.addStyle = function(str) {
var head = document.getElementsByTagName('head').item(0),
style = document.createElement('style'),
rules = document.createTextNode(str);
style.type = 'text/css';
if (style.styleSheet) style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);
};
JSYG.getStyleRules = function() {
var css = '';
function addStyle(rule) { css+=rule.cssText; }
JSYG.makeArray(document.styleSheets).forEach(function(styleSheet) {
JSYG.makeArray(styleSheet.cssRules || styleSheet.rules).forEach(addStyle);
});
return css;
};
/**
* Donne la valeur calculée finale de toutes les propriétés CSS sur le premier élément de la collection.
* @returns {Object} objet CSSStyleDeclaration
*/
function getComputedStyle(node) {
return window.getComputedStyle && window.getComputedStyle(node) || node.currentStyle;
}
/**
* Retire l'attribut de style "style" + tous les attributs svg concernant le style.
*/
JSYG.prototype.styleRemove = function() {
this.each(function() {
var $this = new JSYG(this);
$this.removeAttr('style');
if ($this.isSVG()) JSYG.svgCssProperties.forEach(function(attr) { $this.removeAttr(attr); });
});
return this;
};
/**
* Sauvegarde le style pour être rétabli plus tard par la méthode styleRestore
* @param id identifiant de la sauvegarde du style (pour ne pas interférer avec d'autres styleSave)
* @returns {JSYG}
*/
JSYG.prototype.styleSave = function(id) {
var prop = "styleSaved";
if (id) prop+=id;
this.each(function() {
var $this = new JSYG(this),
attrs={},
style;
if ($this.isSVG()) {
JSYG.svgCssProperties.forEach(function(attr) {
var val = $this.attr(attr);
if (val!= null) attrs[attr] = val;
});
}
style = $this.attr('style');
if (typeof style == 'object') style = JSON.stringify(style); //IE
attrs.style = style;
$this.data(prop,attrs);
});
return this;
};
/**
* Restaure le style préalablement sauvé par la méthode styleSave.
* Attention avec des éléments html et Google Chrome la méthode est asynchrone.
* @param id identifiant de la sauvegarde du style (pour ne pas interférer avec d'autres styleSave)
* @returns {JSYG}
*/
JSYG.prototype.styleRestore = function(id) {
var prop = "styleSaved";
if (id) prop+=id;
this.each(function() {
var $this = new JSYG(this),
attrs = $this.data(prop),
style;
if (!attrs) return;
$this.styleRemove();
if ($this.isSVG()) $this.attr(attrs);
else {
try {
style = JSON.parse(attrs.style);
for (var n in style) { if (style[n]) this.style[n] = style[n]; }
}
catch(e) { $this.attr('style',attrs.style); }
}
$this.removeData(prop);
});
return this;
};
/**
* Applique aux éléments de la collection tous les éléments de style de l'élément passé en argument.
* @param elmt argument JSYG
* @returns {JSYG}
*/
JSYG.prototype.styleClone = function(elmt) {
elmt = new JSYG(elmt);
var foreignStyle = getComputedStyle(elmt[0]),
name,value,
i=0,N=foreignStyle.length;
this.styleRemove();
this.each(function() {
var $this = new JSYG(this),
ownStyle = getComputedStyle(this),
isSVG = $this.isSVG();
for (i=0;i<N;i++) {
name = foreignStyle.item(i);
if (isSVG && JSYG.svgCssProperties.indexOf(name)===-1) continue;
value = foreignStyle.getPropertyValue(name);
//priority = foreignStyle.getPropertyPriority(name);
if (ownStyle.getPropertyValue(name) !== value) {
//ownStyle.setProperty(name,value,priority); //-> Modifications are not allowed for this document (?)
$this.css(name,value);
}
}
});
return this;
};
function addTransform(rect,mtx) {
if (!mtx.isIdentity()) {
var hg = new Vect(0,0).mtx(mtx),
hd = new Vect(rect.width,0).mtx(mtx),
bg = new Vect(0,rect.height).mtx(mtx),
bd = new Vect(rect.width,rect.height).mtx(mtx),
xmin = Math.min(hg.x,hd.x,bg.x,bd.x),
ymin = Math.min(hg.y,hd.y,bg.y,bd.y),
xmax = Math.max(hg.x,hd.x,bg.x,bd.x),
ymax = Math.max(hg.y,hd.y,bg.y,bd.y);
return {
x : Math.round(xmin + rect.x),
y : Math.round(ymin + rect.y),
width : Math.round(xmax - xmin),
height : Math.round(ymax - ymin)
};
}
else return rect;
}
function getPos(type,node,ref) {
var cpt=0,obj=node;
do {cpt+=obj['offset'+type];} while ((obj = obj.offsetParent) && obj!==ref);
return cpt;
}
function swapDisplay(jNode,callback) {
var returnValue;
jNode.styleSave('swapDisplay');
jNode.css({
"visibility":"hidden",
"position":"absolute",
"display": jNode.originalDisplay()
});
try { returnValue = callback.call(jNode); }
catch (e) {
jNode.styleRestore('swapDisplay');
throw new Error(e);
}
jNode.styleRestore('swapDisplay');
return returnValue;
}
/**
* Display par défaut des éléments
*/
var elementDisplay = {};
/**
* Renvoie le display par défaut de l'élément. Tir� de zepto.js. Peut mieux faire.
*/
function defaultDisplay(obj) {
var element, display,
nodeName = obj.getTag(),
isSVG = obj.isSVG(),
parent;
if (!elementDisplay[nodeName]) {
parent = (isSVG) ? new JSYG('<svg>').appendTo('body') : 'body';
element = new JSYG('<'+nodeName+'>').appendTo(parent);
display = element.css('display');
if (isSVG) parent.remove();
else element.remove();
if (display == "none") display = "block";
elementDisplay[nodeName] = display;
}
return elementDisplay[nodeName];
}
JSYG.prototype.originalDisplay = function(_value) {
var prop = "originalDisplay";
if (_value == null) return this.data(prop) || defaultDisplay(this);
else { this.data(prop,_value); return this; }
};
/**
* Récupération des dimensions de l'élément sous forme d'objet avec les propriétés x,y,width,height.
* Pour les éléments HTML, Les dimensions prennent en compte padding, border mais pas margin.<br/><br/>
* Pour les éléments SVG (balises <svg> comprises), ce sont les dimensions sans tenir compte de l'épaisseur du tracé (stroke-width)
* @param type
* <ul>
* <li>null : dimensions avant toute transformation par rapport au parent positionné (viewport pour les éléments svg)</li>
* <li>"page" : dimensions dans la page</li>
* <li>"screen" : dimensions à l'écran</li>
* <li>objet DOM : dimensions relativement à cet objet</li>
* @returns {Object} objet avec les propriétés x,y,width,height
*/
JSYG.prototype.getDim = function(type) {
var node = this[0],
dim=null,parent,box,boundingRect,
hg,hd,bg,bd,
x,y,width,height,
viewBox,jWin,ref,dimRef,
mtx,
tag = this[0].tagName;
if (node.nodeType == 1 && this.css("display") == "none") {
return swapDisplay(this,function() { return this.getDim(); });
}
if (isWindow(node)) {
dim = {
x : node.pageXOffset || document.documentElement.scrollLeft,
y : node.pageYOffset || document.documentElement.scrollTop,
width : node.document.documentElement.clientWidth,
height : node.document.documentElement.clientHeight
};
}
else if (node.nodeType === 9) {
dim = {
x : 0,
y : 0,
width : Math.max(node.documentElement.scrollWidth,node.documentElement.clientWidth,node.body && node.body.scrollWidth || 0),
height : Math.max(node.documentElement.scrollHeight,node.documentElement.clientHeight,node.body && node.body.scrollHeight || 0)
};
}
else if (!node.parentNode) throw new Error(node+" : Il faut d'abord attacher l'élément au DOM.");
else if (!type) {
if (this.isSVG()) {
if (tag == 'svg') {
parent = this.parent();
if (parent.isSVG()) {
dim = {
x : parseFloat(this.attr('x')) || 0,
y : parseFloat(this.attr('y')) || 0,
width : parseFloat(this.attr('width')),
height : parseFloat(this.attr('height'))
};
}
else {
if (parent.css('position') == 'static') parent = parent.offsetParent();
dim = this.getDim(parent);
}
}
else {
try { box = this[0].getBBox(); }
catch(e) { return null; }
dim = { //box est en lecture seule
x : box.x,
y : box.y,
width : box.width,
height : box.height
};
if (tag === 'use' && !JSYG.support.svgUseBBox) {
//bbox fait alors référence à l'élément source donc il faut ajouter les attributs de l'élément lui-même
dim.x += parseFloat(this.attr('x')) || 0;
dim.y += parseFloat(this.attr('y')) || 0;
}
//}
}
} else {
dim = this.getDim( this.offsetParent() );
}
}
else if (type === 'page') {
if (tag === 'svg') {
x = parseFloat(this.css("left") || this.attr('x')) || 0;
y = parseFloat(this.css("top") || this.attr('y')) || 0;
width = parseFloat(this.css("width"));
height = parseFloat(this.css("height"));
viewBox = this.attr("viewBox");
if (viewBox) this.removeAttr("viewBox");
mtx = this.getMtx('screen');
if (viewBox) this.attr("viewBox",viewBox);
hg = new Vect(x,y).mtx(mtx);
bd = new Vect(x+width,y+height).mtx(mtx);
boundingRect = {
left : hg.x,
top : hg.y,
width: bd.x - hg.x,
height : bd.y - hg.y
};
} else {
if (this.isSVG() && this.rotate() === 0) {
//sans rotation, cette méthode est meilleure car getBoundingClientRect
//tient compte de l'épaisseur de tracé (stroke-width)
mtx = this[0].getScreenCTM();
box = this.getDim();
hg = new Vect(box.x,box.y).mtx(mtx);
bd = new Vect(box.x+box.width,box.y+box.height).mtx(mtx);
boundingRect = { left : hg.x, right : bd.x, top : hg.y, bottom : bd.y };
} else boundingRect = node.getBoundingClientRect();
}
jWin = new JSYG(window);
x = boundingRect.left + jWin.scrollLeft() - document.documentElement.clientLeft;
y = boundingRect.top + jWin.scrollTop() - document.documentElement.clientTop;
width = boundingRect.width != null ? boundingRect.width : boundingRect.right - boundingRect.left;
height = boundingRect.height != null ? boundingRect.height : boundingRect.bottom - boundingRect.top;
dim = {
x : x,
y : y,
width : width,
height : height
};
if (!this.isSVG() && JSYG.support.addTransfForBoundingRect) { dim = addTransform(dim,this.getMtx()); } //FF
}
else if (type === 'screen' || isWindow(type) || (type instanceof $ && isWindow(type[0]) ) ) {
jWin = new JSYG(window);
dim = this.getDim('page');
dim.x-=jWin.scrollLeft();
dim.y-=jWin.scrollTop();
}
else if (type.nodeType!=null || type instanceof $) {
ref = type.nodeType!=null ? type : type[0];
if (this.isSVG()) {
if (this.isSVGroot()) {
dimRef = new JSYG(ref).getDim('page');
dim = this.getDim('page');
dim.x -= dimRef.x;
dim.y -= dimRef.y;
}
else {
box = this.getDim();
mtx = this.getMtx(ref);
if (!mtx.isIdentity()) {
hg = new Vect(box.x,box.y).mtx(mtx);
hd = new Vect(box.x+box.width,box.y).mtx(mtx);
bg = new Vect(box.x,box.y+box.height).mtx(mtx);
bd = new Vect(box.x+box.width,box.y+box.height).mtx(mtx);
x = Math.min(hg.x,hd.x,bg.x,bd.x);
y = Math.min(hg.y,hd.y,bg.y,bd.y);
width = Math.max(hg.x,hd.x,bg.x,bd.x)-x;
height = Math.max(hg.y,hd.y,bg.y,bd.y)-y;
dim = { x:x, y:y, width:width, height:height };
} else { dim = box; }
}
} else {
width = node.offsetWidth;
height = node.offsetHeight;
if (!width && !height) {
width = parseFloat(this.css('border-left-width') || 0) + parseFloat(this.css('border-right-width') || 0);
height = parseFloat(this.css('border-top-width') || 0) + parseFloat(this.css('border-top-width') || 0);
if (node.clientWidth || node.clientHeight) {
width+= node.clientWidth;
height+= node.clientHeight;
}
else if (node.width || node.height) {
width+= parseFloat(this.css('padding-left') || 0) + parseFloat(this.css('padding-right') || 0) + node.width;
height+= parseFloat(this.css('padding-top') || 0) + parseFloat(this.css('padding-bottom') || 0) + node.height;
height+= node.clientHeight;
}
}
dim = {
x : getPos('Left',node,ref),
y : getPos('Top',node,ref),
width : width,
height : height
};
}
}
else throw new Error(type+' : argument incorrect');
return dim;
};
/**
* Permet de savoir s'il s'agit d'une balise <image> faisant référence à du contenu svg, car auquel cas elle
* se comporte plus comme un conteneur (du moins avec firefox).
*/
function isSVGImage(elmt) {
return elmt[0].tagName == 'image' && /(image\/svg\+xml|\.svg$)/.test(elmt.href());
}
function parseDimArgs(args,opt) {
['x','y','width','height'].forEach(function(prop,i) {
if (args[i]!=null) { opt[prop] = args[i]; }
});
}
function getPropNum(elmt,prop) {
var val = elmt.css(prop);
if (!val) return 0;
else if (val != "auto") return parseFloat(val);
else if (prop == "left" || prop == "top") return elmt.position()[prop];
else return 0;
}
/**
* définit les dimensions de la collection par rapport au parent positionné, avant transformation.
* Pour les éléments HTML, Les dimensions prennent en compte padding, border mais pas margin.<br/><br/>
* Pour les éléments SVG (balises <svg> comprises), ce sont les dimensions sans tenir compte de l'épaisseur du tracé (stroke-width).<br/><br/>
* En argument, au choix :
* <ul>
* <li>1 argument : objet avec les propriétés parmi x,y,width,height.</li>
* <li>2 arguments : nom de la propriété parmi x,y,width,height et valeur.</li>
* <li>4 arguments : valeurs de x,y,width et height. On peut passer null pour ignorer une valeur.</li>
* </ul>
* @returns {JSYG}
* @example <pre> new JSYG('#monElement').setDim({x:50,y:50,width:250,height:300});
*
* //équivalent à :
* new JSYG('#monElement').setDim("x",50).setDim("y",50).setDim("width",250).setDim("height",300);
*
* //équivalent à :
* new JSYG('#monElement').setDim(50,50,250,300);
*/
JSYG.prototype.setDim = function() {
var opt = {},
n = null, a = arguments,
ref;
switch (typeof a[0]) {
case 'string' : opt[ a[0] ] = a[1]; break;
case 'number' : parseDimArgs(a,opt); break;
case 'object' :
if (a[0] == null) parseDimArgs(a,opt);
else {
for (n in a[0]) opt[n] = a[0][n];
}
break;
default : throw new Error("argument(s) incorrect(s) pour la méthode setDim");
}
ref = opt.from && new JSYG(opt.from);
this.each(function() {
var tag, dim, mtx, box, dec, decx, decy, position,
$this = new JSYG(this),
node = this;
if (opt.keepRatio && ('width' in opt || 'height' in opt)) {
dim = $this.getDim();
if (!('width' in opt)) opt.width = dim.width * opt.height / dim.height;
else if (!('height' in opt)) opt.height = dim.height * opt.width / dim.width;
}
if (isWindow(node) || node.nodeType === 9) {
$this.getWindow().resizeTo( parseFloat(opt.width) || 0, parseFloat(opt.height) || 0 );
return;
}
tag = this.tagName;
if ('from' in opt) {
mtx = $this.getMtx(ref).inverse();
dim = $this.getDim();
var dimRef = $this.getDim(ref),
x = (opt.x == null) ? 0 : opt.x,
y = (opt.y == null) ? 0 : opt.y,
xRef = (opt.x == null) ? 0 : dimRef.x,
yRef = (opt.y == null) ? 0 : dimRef.y,
width = (opt.width == null) ? 0 : opt.width,
height = (opt.height == null) ? 0 : opt.height,
widthRef = (opt.width == null) ? 0 : dimRef.width,
heightRef = (opt.height == null) ? 0 : dimRef.height,
pt1 = new Vect(xRef,yRef).mtx(mtx),
pt2 = new Vect(x,y).mtx(mtx),
pt3 = new Vect(widthRef,heightRef).mtx(mtx),
pt4 = new Vect(width,height).mtx(mtx),
newDim = {};
if (tag == "g") mtx = $this.getMtx();
if (opt.x!=null || opt.y!=null) {
newDim.x = dim.x + pt2.x - pt1.x;
newDim.y = dim.y + pt2.y - pt1.y;
}
if (opt.width!=null || opt.height!=null) {
newDim.width = dim.width + pt4.x - pt3.x;
newDim.height = dim.height + pt4.y - pt3.y;
}
$this.setDim(newDim);
if (tag == "g") $this.setMtx( mtx.multiply($this.getMtx()) );
return;
}
switch (tag) {
case 'circle' :
if ("width" in opt) {
node.setAttribute('cx',(node.getAttribute('cx') || 0)-(node.getAttribute('r') || 0)+opt.width/2);
node.setAttribute('r',opt.width/2);
}
if ("height" in opt) {
node.setAttribute('cy',(node.getAttribute('cy') || 0)-(node.getAttribute('r') || 0)+opt.height/2);
node.setAttribute('r',opt.height/2);
}
if ("x" in opt) node.setAttribute('cx',opt.x + parseFloat(node.getAttribute('r') || 0));
if ("y" in opt) node.setAttribute('cy',opt.y + parseFloat(node.getAttribute('r') || 0));
break;
case 'ellipse' :