summaryrefslogtreecommitdiffstats
path: root/src/image.js
blob: 6f8ba5b70f017c12bc979ec60b2f66ccc842f931 (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
SVG.Image = SVG.invent({
  // Initialize node
  create: 'image'

  // Inherit from
, inherit: SVG.Shape

  // Add class methods
, extend: {
    // (re)load image
    load: function(url, callback) {
      if (!url) return this

      var img = new window.Image()

      SVG.on(img, 'load', function(e) {
        var p = this.parent(SVG.Pattern)

        // ensure image size
        if (this.width() == 0 && this.height() == 0)
          this.size(img.width, img.height)

        if(p instanceof SVG.Pattern) {
          // ensure pattern size if not set
          if (p.width() == 0 && p.height() == 0)
            p.size(this.width(), this.height())
        }

        if(typeof callback == 'function') {
          callback.call(this, {
            width:  img.width
          , height: img.height
          , ratio:  img.width / img.height
          , url:    url
          })
        }
      }, this)

      SVG.on(img, 'load error', function() {
        // dont forget to unbind memory leaking events
        SVG.off(img)
      })

      return this.attr('href', (img.src = url), SVG.xlink)
    }
  }

  // Add parent method
, construct: {
    // create image element, load image and set its size
    image: function(source, callback) {
      return this.put(new SVG.Image).size(0, 0).load(source, callback)
    }
  }
})