aboutsummaryrefslogtreecommitdiffstats
path: root/src/elements/Mask.js
blob: 523b9deb803c95aba97a7b35de89439186d8a304 (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
import { nodeOrNew, register, wrapWithAttrCheck } from '../utils/adopter.js'
import { registerMethods } from '../utils/methods.js'
import Container from './Container.js'
import baseFind from '../modules/core/selector.js'

export default class Mask extends Container {

  // Initialize node
  constructor ( node ) {

    super( nodeOrNew( 'mask', node ), node )

  }

  // Unmask all masked elements and remove itself
  remove () {

    // unmask all targets
    this.targets().forEach( function ( el ) {

      el.unmask()

    } )

    // remove mask from parent
    return super.remove()

  }

  targets () {

    return baseFind( 'svg [mask*="' + this.id() + '"]' )

  }

}

registerMethods( {
  Container: {
    mask: wrapWithAttrCheck( function () {

      return this.defs().put( new Mask() )

    } )
  },
  Element: {
    // Distribute mask to svg element
    maskWith ( element ) {

      // use given mask or create a new one
      var masker = element instanceof Mask
        ? element
        : this.parent().mask().add( element )

      // apply mask
      return this.attr( 'mask', 'url("#' + masker.id() + '")' )

    },

    // Unmask element
    unmask () {

      return this.attr( 'mask', null )

    },

    masker () {

      return this.reference( 'mask' )

    }
  }
} )

register( Mask )