summaryrefslogtreecommitdiffstats
path: root/src/doc.js
blob: 820a8cd0fd95b1e8edc65718cd9257a655246dd8 (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
SVG.Doc = SVG.invent({
  // Initialize node
  create: function(element) {
    /* ensure the presence of a html element */
    this.parent = typeof element == 'string' ?
      document.getElementById(element) :
      element
    
    /* If the target is an svg element, use that element as the main wrapper.
       This allows svg.js to work with svg documents as well. */
    this.constructor
      .call(this, this.parent.nodeName == 'svg' ? this.parent : SVG.create('svg'))
    
    /* set svg element attributes */
    this
      .attr({ xmlns: SVG.ns, version: '1.1', width: '100%', height: '100%' })
      .attr('xmlns:xlink', SVG.xlink, SVG.xmlns)
    
    /* create the <defs> node */
    this._defs = new SVG.Defs
    this._defs.parent = this
    this.node.appendChild(this._defs.node)

    /* turn off sub pixel offset by default */
    this.doSpof = false
    
    /* ensure correct rendering */
    if (this.parent != this.node)
      this.stage()
  }

  // Inherit from
, inherit: SVG.Container

  // Add class methods
, extend: {
    /* enable drawing */
    stage: function() {
      var element = this

      /* insert element */
      this.parent.appendChild(this.node)

      /* fix sub-pixel offset */
      element.spof()
      
      /* make sure sub-pixel offset is fixed every time the window is resized */
      SVG.on(window, 'resize', function() {
        element.spof()
      })

      return this
    }

    // Creates and returns defs element
  , defs: function() {
      return this._defs
    }

    // Fix for possible sub-pixel offset. See:
    // https://bugzilla.mozilla.org/show_bug.cgi?id=608812
  , spof: function() {
      if (this.doSpof) {
        var pos = this.node.getScreenCTM()
        
        if (pos)
          this
            .style('left', (-pos.e % 1) + 'px')
            .style('top',  (-pos.f % 1) + 'px')
      }
      
      return this
    }

    // Enable sub-pixel offset
  , fixSubPixelOffset: function() {
      this.doSpof = true

      return this
    }
    
      // Removes the doc from the DOM
  , remove: function() {
      if(this.parent) {
        this.parent.removeChild(this.node);
        this.parent = null;
      }

      return this;
    }
  }
  
})