getMatrix2D有用吗?

用于Dom Transformation时候,可以用于兼容不支持CSS3 3D Transforms的浏览器

如,我们可以很轻松的把一些transformation属性转换成CSS3属性赋给DOM:

  1. var matrix = Transform.getMatrix2D({
  2. rotation: 30,
  3. scaleX: 0.5,
  4. scaleY: 0.5,
  5. translateX: 100
  6. })
  7. ele.style.transform = ele.style.msTransform = ele.style.OTransform = ele.style.MozTransform = ele.style.webkitTransform = "matrix(" + [matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty].join(",") + ")"

用于Canvas和SVG Transformation

什么?还能用于Canvas和SVG?是的,举个例子,在Canvas画一个旋转30度、缩小成0.5倍,并且平移(200,200)的图片:

  1. var canvas = document.getElementById("ourCanvas"),
  2. ctx = canvas.getContext("2d"),
  3. img = new Image(),
  4. rotation = 30 * Math.PI / 180
  5. img.onload = function () {
  6. ctx.sava()
  7. ctx.setTransform(
  8. 0.5 * Math.cos(rotation), 0.5 * Math.sin(rotation),
  9. -0.5 * Math.sin(rotation), 0.5 * Math.cos(rotation),
  10. 200, 200
  11. )
  12. ctx.drawImage(img, 0, 0)
  13. ctx.restore()
  14. };
  15. img.src = "asset/img/test.png"

上面是我们传统的姿势。使用Transform.getMatrix2D 之后,变成这个样子:

  1. var canvas = document.getElementById("ourCanvas"),
  2. ctx = canvas.getContext("2d"),
  3. img = new Image()
  4. var matrix = Transform.getMatrix2D({
  5. rotation: 30,
  6. scaleX: 0.5,
  7. scaleY: 0.5,
  8. translateX: 200,
  9. translateY: 200
  10. })
  11. img.onload = function () {
  12. ctx.sava()
  13. ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty)
  14. ctx.drawImage(img, 0, 0)
  15. ctx.restore()
  16. }
  17. img.src = "asset/img/test.png"

可以看到,这里让开发者不用自己去拼凑matrix。SVG的粒子就不再举例,和用于DOM的例子差不多,相信大家能够很快搞定。