aboutsummaryrefslogtreecommitdiffstats
path: root/src/matrix.js
blob: 31d3d58a97a8a4a29c836610b79a8512e2ba9114 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/* global abcdef, arrayToMatrix, closeEnough, formatTransforms */

SVG.Matrix = SVG.invent({
  // Initialize
  create: function (source) {
    var base = arrayToMatrix([1, 0, 0, 1, 0, 0])

    // ensure source as object
    source = source instanceof SVG.Element ? source.matrixify()
      : typeof source === 'string' ? arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat))
      : Array.isArray(source) ? arrayToMatrix(source)
      : (typeof source === 'object' && (
          source.a != null || source.b != null || source.c != null ||
          source.d != null || source.e != null || source.f != null
        )) ? source
      : (typeof source === 'object') ? new SVG.Matrix().transform(source)
      : arguments.length === 6 ? arrayToMatrix([].slice.call(arguments))
      : base

    // Merge the source matrix with the base matrix
    this.a = source.a != null ? source.a : base.a
    this.b = source.b != null ? source.b : base.b
    this.c = source.c != null ? source.c : base.c
    this.d = source.d != null ? source.d : base.d
    this.e = source.e != null ? source.e : base.e
    this.f = source.f != null ? source.f : base.f
  },

  // Add methods
  extend: {

    // Clones this matrix
    clone: function () {
      return new SVG.Matrix(this)
    },

    // Transform a matrix into another matrix by manipulating the space
    transform: function (o) {
      // Check if o is a matrix and then left multiply it directly
      if (o.a != null) {
        var matrix = new SVG.Matrix(o)
        var newMatrix = this.lmultiply(matrix)
        return newMatrix
      }

      // Get the proposed transformations and the current transformations
      var t = formatTransforms(o)
      var currentTransform = new SVG.Matrix(this)

      // Construct the resulting matrix
      var transformer = new SVG.Matrix()
        .translate(-t.ox, -t.oy)
        .scale(t.scaleX, t.scaleY)
        .skew(t.skewX, t.skewY)
        .shear(t.shear)
        .rotate(t.theta)
        .translate(t.ox, t.oy)
        .translate(t.rx, t.ry)
        .lmultiply(currentTransform)

      // If we want the origin at a particular place, we force it there
      if (isFinite(t.px) || isFinite(t.py)) {
        // Figure out where the origin went and the delta to get there
        var current = new SVG.Point(t.ox - t.rx, t.oy - t.ry).transform(transformer)
        var dx = t.px ? t.px - current.x : 0
        var dy = t.py ? t.py - current.y : 0

        // Apply another translation
        transformer = transformer.translate(dx, dy)
      }

      // We can apply translations after everything else
      transformer = transformer.translate(t.tx, t.ty)
      return transformer
    },

    // Applies a matrix defined by its affine parameters
    compose: function (o) {
      if (o.origin) {
        o.originX = o.origin[0]
        o.originY = o.origin[1]
      }
      // Get the parameters
      var ox = o.originX || 0
      var oy = o.originY || 0
      var sx = o.scaleX || 1
      var sy = o.scaleY || 1
      var lam = o.shear || 0
      var theta = o.rotate || 0
      var tx = o.translateX || 0
      var ty = o.translateY || 0

      // Apply the standard matrix
      var result = new SVG.Matrix()
        .translate(-ox, -oy)
        .scale(sx, sy)
        .shear(lam)
        .rotate(theta)
        .translate(tx, ty)
        .lmultiply(this)
        .translate(ox, oy)
      return result
    },

    // Decomposes this matrix into its affine parameters
    decompose: function (cx=0, cy=0) {
      // Get the parameters from the matrix
      var a = this.a
      var b = this.b
      var c = this.c
      var d = this.d
      var e = this.e
      var f = this.f

      // Figure out if the winding direction is clockwise or counterclockwise
      var determinant = a * d - b * c
      var ccw = determinant > 0 ? 1 : -1

      // Since we only shear in x, we can use the x basis to get the x scale
      // and the rotation of the resulting matrix
      var sx = ccw * Math.sqrt(a * a + b * b)
      var thetaRad = Math.atan2(ccw * b, ccw * a)
      var theta = 180 / Math.PI * thetaRad
      var ct = Math.cos(thetaRad)
      var st = Math.sin(thetaRad)

      // We can then solve the y basis vector simultaneously to get the other
      // two affine parameters directly from these parameters
      var lam = (a * c + b * d) / determinant
      var sy = ((c * sx) / (lam * a - b)) || ((d * sx) / (lam * b + a))

      let tx = e - cx + cx * ct * sx + cy * (lam * ct * sx - st * sy)
      let ty = f - cy + cx * st * sx + cy * (lam * st * sx + ct * sy)

      // Construct the decomposition and return it
      return {
        // Return the affine parameters
        scaleX: sx,
        scaleY: sy,
        shear: lam,
        rotate: theta,
        translateX: tx,
        translateY: ty,
        originX: cx,
        originY: cy,

        // Return the matrix parameters
        a: this.a,
        b: this.b,
        c: this.c,
        d: this.d,
        e: this.e,
        f: this.f
      }
    },

    // Morph one matrix into another
    morph: function (matrix) {
      // Store new destination
      this.destination = new SVG.Matrix(matrix)
      return this
    },

    // Get morphed matrix at a given position
    at: function (pos) {
      // Make sure a destination is defined
      if (!this.destination) return this

      // Calculate morphed matrix at a given position
      var matrix = new SVG.Matrix({
        a: this.a + (this.destination.a - this.a) * pos,
        b: this.b + (this.destination.b - this.b) * pos,
        c: this.c + (this.destination.c - this.c) * pos,
        d: this.d + (this.destination.d - this.d) * pos,
        e: this.e + (this.destination.e - this.e) * pos,
        f: this.f + (this.destination.f - this.f) * pos
      })

      return matrix
    },

    // Left multiplies by the given matrix
    multiply: function (matrix) {
      // Get the matrices
      var l = this
      var r = new SVG.Matrix(matrix)

      // Work out the product directly
      var a = l.a * r.a + l.c * r.b
      var b = l.b * r.a + l.d * r.b
      var c = l.a * r.c + l.c * r.d
      var d = l.b * r.c + l.d * r.d
      var e = l.e + l.a * r.e + l.c * r.f
      var f = l.f + l.b * r.e + l.d * r.f

      // Form the matrix and return it
      var product = new SVG.Matrix(a, b, c, d, e, f)
      return product
    },

    lmultiply: function (matrix) {
      var result = new SVG.Matrix(matrix).multiply(this)
      return result
    },

    // Inverses matrix
    inverse: function () {
      // Get the current parameters out of the matrix
      var a = this.a
      var b = this.b
      var c = this.c
      var d = this.d
      var e = this.e
      var f = this.f

      // Invert the 2x2 matrix in the top left
      var det = a * d - b * c
      if (!det) throw new Error('Cannot invert ' + this)

      // Calculate the top 2x2 matrix
      var na = d / det
      var nb = -b / det
      var nc = -c / det
      var nd = a / det

      // Apply the inverted matrix to the top right
      var ne = -(na * e + nc * f)
      var nf = -(nb * e + nd * f)

      // Construct the inverted matrix
      return new SVG.Matrix(na, nb, nc, nd, ne, nf)
    },

    // Translate matrix
    translate: function (x, y) {
      return new SVG.Matrix(this).translateO(x, y)
    },

    translateO: function (x, y) {
      this.e += x || 0
      this.f += y || 0
      return this
    },

    // Scale matrix
    scale: function (x, y, cx, cy) {
      // Support uniform scaling
      if (arguments.length === 1) {
        y = x
      } else if (arguments.length === 3) {
        cy = cx
        cx = y
        y = x
      }

      // Scale the current matrix
      var scale = new SVG.Matrix(x, 0, 0, y, 0, 0)
      var matrix = this.around(cx, cy, scale)
      return matrix
    },

    // Rotate matrix
    rotate: function (r, cx, cy) {
      // Convert degrees to radians
      r = SVG.utils.radians(r)

      // Construct the rotation matrix
      var rotation = new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0)
      var matrix = this.around(cx, cy, rotation)
      return matrix
    },

    // Flip matrix on x or y, at a given offset
    flip: function (axis, around) {
      return axis === 'x' ? this.scale(-1, 1, around, 0)
        : axis === 'y' ? this.scale(1, -1, 0, around)
        : this.scale(-1, -1, axis, around || axis) // Define an x, y flip point
    },

    // Shear matrix
    shear: function (a, cx, cy) {
      var shear = new SVG.Matrix(1, 0, a, 1, 0, 0)
      var matrix = this.around(cx, cy, shear)
      return matrix
    },

    // Skew Matrix
    skew: function (x, y, cx, cy) {
      // support uniformal skew
      if (arguments.length === 1) {
        y = x
      } else if (arguments.length === 3) {
        cy = cx
        cx = y
        y = x
      }

      // Convert degrees to radians
      x = SVG.utils.radians(x)
      y = SVG.utils.radians(y)

      // Construct the matrix
      var skew = new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0)
      var matrix = this.around(cx, cy, skew)
      return matrix
    },

    // SkewX
    skewX: function (x, cx, cy) {
      return this.skew(x, 0, cx, cy)
    },

    // SkewY
    skewY: function (y, cx, cy) {
      return this.skew(0, y, cx, cy)
    },

    // Transform around a center point
    around: function (cx, cy, matrix) {
      var dx = cx || 0
      var dy = cy || 0
      return this.translate(-dx, -dy).lmultiply(matrix).translate(dx, dy)
    },

    // Convert to native SVGMatrix
    native: function () {
      // create new matrix
      var matrix = SVG.parser.nodes.svg.node.createSVGMatrix()

      // update with current values
      for (var i = abcdef.length - 1; i >= 0; i--) {
        matrix[abcdef[i]] = this[abcdef[i]]
      }

      return matrix
    },

    // Check if two matrices are equal
    equals: function (other) {
      var comp = new SVG.Matrix(other)
      return closeEnough(this.a, comp.a) && closeEnough(this.b, comp.b) &&
        closeEnough(this.c, comp.c) && closeEnough(this.d, comp.d) &&
        closeEnough(this.e, comp.e) && closeEnough(this.f, comp.f)
    },

    // Convert matrix to string
    toString: function () {
      return 'matrix(' + this.a + ',' + this.b + ',' + this.c + ',' + this.d + ',' + this.e + ',' + this.f + ')'
    },

    toArray: function () {
      return [this.a, this.b, this.c, this.d, this.e, this.f]
    },

    valueOf: function () {
      return {
        a: this.a,
        b: this.b,
        c: this.c,
        d: this.d,
        e: this.e,
        f: this.f
      }
    }
  },

  // Define parent
  parent: SVG.Element,

  // Add parent method
  construct: {
    // Get current matrix
    ctm: function () {
      return new SVG.Matrix(this.node.getCTM())
    },
    // Get current screen matrix
    screenCTM: function () {
      /* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537
         This is needed because FF does not return the transformation matrix
         for the inner coordinate system when getScreenCTM() is called on nested svgs.
         However all other Browsers do that */
      if (this instanceof SVG.Doc && !this.isRoot()) {
        var rect = this.rect(1, 1)
        var m = rect.node.getScreenCTM()
        rect.remove()
        return new SVG.Matrix(m)
      }
      return new SVG.Matrix(this.node.getScreenCTM())
    }
  }
})