summaryrefslogtreecommitdiffstats
path: root/src/ClipPath.js
blob: ef820e57105ac319ce5705c38170927dc89b42fc (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
import Container from './Container.js'
import Element from './Element.js'
import {nodeOrNew, extend} from './tools.js'
import find from './selector.js'

export default class ClipPath extends Container {
  constructor (node) {
    super(nodeOrNew('clipPath', node))
  }

  // Unclip all clipped elements and remove itself
  remove () {
    // unclip all targets
    this.targets().forEach(function (el) {
      el.unclip()
    })

    // remove clipPath from parent
    return super.remove()
  }

  targets () {
    return find('svg [clip-path*="' + this.id() + '"]')
  }
}

addFactory(Container, {
  // Create clipping element
  clip: function() {
    return this.defs().put(new ClipPath)
  }
})

extend(Element, {
  // Distribute clipPath to svg element
  clipWith (element) {
    // use given clip or create a new one
    let clipper = element instanceof ClipPath
      ? element
      : this.parent().clip().add(element)

    // apply mask
    return this.attr('clip-path', 'url("#' + clipper.id() + '")')
  },

  // Unclip element
  unclip () {
    return this.attr('clip-path', null)
  },

  clipper () {
    return this.reference('clip-path')
  }
})