Skip to content

Instantly share code, notes, and snippets.

@c-spencer
Created May 1, 2012 08:58
Show Gist options
  • Save c-spencer/2566559 to your computer and use it in GitHub Desktop.
Save c-spencer/2566559 to your computer and use it in GitHub Desktop.
JS Implementation of SVGMatrix
# JSMatrix is API Compatible with SVGMatrix
PI_DEG = Math.PI/180
class JSMatrix
constructor: (@a, @b, @c, @d, @e, @f) ->
# Multiplication of direct parameters
_mult: (a, b, c, d, e, f) ->
new JSMatrix(
@a * a + @c * b
@b * a + @d * b
@a * c + @c * d
@b * c + @d * d
@a * e + @c * f + @e
@b * e + @d * f + @f
)
# Multiplication of another Matrix
multiply: (m) ->
@_mult m.a, m.b, m.c, m.d, m.e, m.f
translate: (x, y) ->
@_mult 1, 0, 0, 1, x, y
scale: (s) ->
@_mult s, 0, 0, s, 0, 0
scaleNonUniform: (x, y) ->
@_mult x, 0, 0, y, 0, 0
rotate: (degrees) ->
@_rotate degrees * PI_DEG
rotateFromVector: (x, y) ->
@_rotate Math.atan2 y, x
_rotate: (radians) ->
c = Math.cos radians
s = Math.sin radians
@_mult c, s, -s, c, 0, 0
flipX: ->
@_mult -1, 0, 0, 1, 0, 0
flipY: ->
@_mult 1, 0, 0, -1, 0, 0
skewX: (degrees) ->
@_mult 1, 0, Math.tan(degrees * PI_DEG), 1, 0, 0
skewY: (degrees) ->
@_mult 1, Math.tan(degrees * PI_DEG), 0, 1, 0, 0
inverse: ->
det = @a*@d - @c*@b
return null if det == 0
new JSMatrix(
@d / det
-@b / det
-@c / det
@a / det
(@c*@f-@e*@d) / det
(@e*@b-@a*@f) / det
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment