aboutsummaryrefslogtreecommitdiffstats
path: root/src/gradient.js
blob: b9533cb426058359d22cf58e7b7488a20ba0d2bb (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
SVG.Gradient = function Gradient(t) {
  this.constructor.call(this, SVG.create(t + 'Gradient'));
  
  // set unique id
  this.id = 'svgjs_' + (SVG.did++);
  this.attr('id', this.id);
  
  // store type
  this.type = t;
};

// inherit from SVG.Element
SVG.Gradient.prototype = new SVG.Element();

// include the container object
SVG.extend(SVG.Gradient, SVG.Container);

// add gradient-specific functions
SVG.extend(SVG.Gradient, {
  
  // from position
  from: function(x, y) {
    return this.type == 'radial' ?
             this.attr({ fx: x + '%', fy: y + '%' }) :
             this.attr({ x1: x + '%', y1: y + '%' });
  },
  
  // to position
  to: function(x, y) {
    return this.type == 'radial' ?
             this.attr({ cx: x + '%', cy: y + '%' }) :
             this.attr({ x2: x + '%', y2: y + '%' });
  },
  
  // radius for radial gradient
  radius: function(r) {
    return this.type == 'radial' ?
             this.attr({ r: r + '%' }) :
             this;
  },
  
  // add a color stop
  at: function(o) {
    return this.put(new SVG.Stop(o));
  },
  
  // update gradient
  update: function(b) {
    // remove all stops
    while (this.node.hasChildNodes())
      this.node.removeChild(this.node.lastChild);
    
    // invoke passed block
    b(this);
    
    return this;
  },
  
  // return the fill id
  fill: function() {
    return 'url(#' + this.id + ')';
  }
  
});

// add def-specific functions
SVG.extend(SVG.Defs, {
  
  // define clippath
  gradient: function(t, b) {
    var e = this.put(new SVG.Gradient(t));
    
    // invoke passed block
    b(e);
    
    return e;
  }
  
});


SVG.Stop = function Stop(o) {
  this.constructor.call(this, SVG.create('stop'));
  
  // immediatelly build stop
  this.update(o);
};

// inherit from SVG.Element
SVG.Stop.prototype = new SVG.Element();

// add mark-specific functions
SVG.extend(SVG.Stop, {
  
  // add color stops
  update: function(o) {
    var i,
        s = '',
        a = ['opacity', 'color'];
    
    // build style attribute
    for (i = a.length - 1; i >= 0; i--)
      if (o[a[i]] != null)
        s += 'stop-' + a[i] + ':' + o[a[i]] + ';';
    
    // set attributes
    return this.attr({
      offset: (o.offset != null ? o.offset : this.attrs.offset || 0) + '%',
      style:  s
    });
  }
  
});