aboutsummaryrefslogtreecommitdiffstats
path: root/src/element.js
blob: 9536a79d5940470d3f4764c020116620e567abe7 (plain)
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
SVG.Element = function Element(node) {
  this.node = node;
  this.attrs = {};
};

// Add element-specific functions
SVG.Utils.merge(SVG.Element, {
  
  // move element to given x and y values
  move: function(x, y) {
    this.attr('x', x);
    this.attr('y', y);

    return this;
  },

  // set element opacity
  opacity: function(o) {
    return this.attr('opacity', Math.max(0, Math.min(1, o)));
  },

  // set element size to given width and height
  size: function(w, h) {
    this.attr('width', w);
    this.attr('height', h);

    return this;
  },

  // clip element using another element
  clip: function(block) {
    var p = this.parentSVG().defs().clipPath();
    block(p);

    return this.clipTo(p);
  },

  // distribute clipping path to svg element
  clipTo: function(p) {
    return this.attr('clip-path', 'url(#' + p.id + ')');
  },

  // remove element
  remove: function() {
    return this.parent != null ? this.parent.remove(this) : void 0;
  },

  // get parent document
  parentDoc: function() {
    return this._parent(SVG.Doc);
  },

  // get parent svg wrapper
  parentSVG: function() {
    return this.parentDoc();
  },
  
  // set svg element attribute
  attr: function(v) {
    var a = arguments;
    
    this.attrs[a[0]] = a[1];
    
    if (typeof v == 'object')
      for (var k in v)
        this.attr(k, v[k]);
        
    else if (a.length == 2)
      this.node.setAttribute(a[0], a[1]);
      
    else if (a.length == 3)
      this.node.setAttributeNS(a[2], a[0], a[1]);

    return this;
  },

  // get bounding box
  bbox: function() {
    return this.node.getBBox();
  },

  // private: find svg parent
  _parent: function(pt) {
    var e = this;

    while (e != null && !(e instanceof pt))
      e = e.parent;

    return e;
  }
  
});