Skip to content

Calculating 2d Matrices

heygrady edited this page Sep 14, 2010 · 19 revisions

JavaScript doesn’t have anything built-in to handle matrix calculations, however, there is a great library called Sylvester that makes matrices easy.

Standard 2d transformation functions

The CSS3 spec for 2d transformations lists out the common functions. But they didn’t just make them up out of thin air. Each function represents a specific matrix that is used to calculate coordinates on a new object. Apparently this is a common thing that math nerds have know for ages. The SVG spec has a great breakdown of how matrices work.

  • rotate
  • scale
  • scaleX
  • scaleY
  • skew
  • skewX
  • skewY
  • translate
  • translateX
  • translateY
transform: rotate(45deg) skewX(20deg);

Combining transform functions together is equivalent to multiplying matrices together.

Matrix for each function

We’ll use Sylvester to create an object that creates a matrix for each of the functions above.

var Transform = {
    rotate: function(deg) {...},
    scale: function(sx, sy) {...},
    scaleX: function(sx) {...},
    scaleY: function(sy) {...},
    skew: function(degX, degY) {...},
    skewX: function(deg) {...},
    skewY: function(deg) {...},
    translate: function(tx, ty) {...},
    translateX: function(tx) {...},
    translateY: function(ty) {...},
};

Rotate

var Transform = {
    rotate: function(deg) {
        var rad = parseFloat(deg) * (Math.PI/180),
            costheta = Math.cos(rad),
            sintheta = Math.sin(rad);

var a = costheta, b = sintheta, c = -sintheta, d = costheta; return $M([ [a, c, 0], [b, d, 0], [0, 0, 1] ]); }, …

}

Clone this wiki locally