aboutsummaryrefslogtreecommitdiffstats
path: root/src/gradient.js
blob: 6554c92966a50ee3766d2bdcb99cc7f82b33bf40 (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
SVG.Gradient = function Gradient(type) {
  this.constructor.call(this, SVG.create(type + 'Gradient'));
  
  /* set unique id */
  this.attr('id', (this.id = 'svgjs_element_' + (SVG.did++)));
  
  /* store type */
  this.type = type;
};

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

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

//
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(radius) {
    return this.type == 'radial' ?
      this.attr({ r: radius + '%' }) :
      this;
  },
  // Add a color stop
  at: function(stop) {
    return this.put(new SVG.Stop(stop));
  },
  // Update gradient
  update: function(block) {
    /* remove all stops */
    while (this.node.hasChildNodes())
      this.node.removeChild(this.node.lastChild);
    
    /* invoke passed block */
    block(this);
    
    return this;
  },
  // Return the fill id
  fill: function() {
    return 'url(#' + this.id + ')';
  }
  
});

//
SVG.extend(SVG.Defs, {
  
  /* define gradient */
  gradient: function(type, block) {
    var element = this.put(new SVG.Gradient(type));
    
    /* invoke passed block */
    block(element);
    
    return element;
  }
  
});


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

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

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