getMatrix2D有用吗?
用于Dom Transformation时候,可以用于兼容不支持CSS3 3D Transforms的浏览器
如,我们可以很轻松的把一些transformation属性转换成CSS3属性赋给DOM:
var matrix = Transform.getMatrix2D({
rotation: 30,
scaleX: 0.5,
scaleY: 0.5,
translateX: 100
})
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)的图片:
var canvas = document.getElementById("ourCanvas"),
ctx = canvas.getContext("2d"),
img = new Image(),
rotation = 30 * Math.PI / 180
img.onload = function () {
ctx.sava()
ctx.setTransform(
0.5 * Math.cos(rotation), 0.5 * Math.sin(rotation),
-0.5 * Math.sin(rotation), 0.5 * Math.cos(rotation),
200, 200
)
ctx.drawImage(img, 0, 0)
ctx.restore()
};
img.src = "asset/img/test.png"
上面是我们传统的姿势。使用Transform.getMatrix2D 之后,变成这个样子:
var canvas = document.getElementById("ourCanvas"),
ctx = canvas.getContext("2d"),
img = new Image()
var matrix = Transform.getMatrix2D({
rotation: 30,
scaleX: 0.5,
scaleY: 0.5,
translateX: 200,
translateY: 200
})
img.onload = function () {
ctx.sava()
ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty)
ctx.drawImage(img, 0, 0)
ctx.restore()
}
img.src = "asset/img/test.png"
可以看到,这里让开发者不用自己去拼凑matrix。SVG的粒子就不再举例,和用于DOM的例子差不多,相信大家能够很快搞定。