aboutsummaryrefslogtreecommitdiffstats
path: root/src/mask.js
blob: e40d80f41da45015d2418a3df833220460c2769f (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
SVG.Mask = SVG.invent({
  // Initialize node
  create: 'mask',

  // Inherit from
  inherit: SVG.Container,

  // Add class methods
  extend: {
    // Unmask all masked elements and remove itself
    remove: function () {
      // unmask all targets
      this.targets().forEach(function (el) {
        el.unmask()
      })

      // remove mask from parent
      return SVG.Element.prototype.remove.call(this)
    },

    targets: function () {
      return SVG.select('svg [mask*="' + this.id() + '"]')
    }
  },

  // Add parent method
  construct: {
    // Create masking element
    mask: function () {
      return this.defs().put(new SVG.Mask())
    }
  }
})

SVG.extend(SVG.Element, {
  // Distribute mask to svg element
  maskWith: function (element) {
    // use given mask or create a new one
    var masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element)

    // apply mask
    return this.attr('mask', 'url("#' + masker.id() + '")')
  },
  // Unmask element
  unmask: function () {
    return this.attr('mask', null)
  },
  masker: function () {
    return this.reference('mask')
  }
})