summaryrefslogtreecommitdiffstats
path: root/src/Image.js
blob: ea46a57ec8d11515c7a31339766e182726861f51 (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
import Shape from './Shape.js'
import Pattern from './Pattern.js'
import {on, off} from './event.js'
import {nodeOrNew} from './tools.js'
import {xlink} from './namespaces.js'
import {register} from './adopter.js'
import {registerMethods} from './methods.js'

export default class Image extends Shape {
  constructor (node) {
    super(nodeOrNew('image', node), Image)
  }

  // (re)load image
  load (url, callback) {
    if (!url) return this

    var img = new window.Image()

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

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

      if (p instanceof 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)

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

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

  attrHook (obj) {
    return obj.doc().defs().pattern(0, 0, (pattern) => {
      pattern.add(this)
    })
  }
}

registerMethods({
  Container: {
    // create image element, load image and set its size
    image (source, callback) {
      return this.put(new Image()).size(0, 0).load(source, callback)
    }
  }
})

register(Image)