前言在我的另一篇博文 Canvas坐标系转换 中,我们知道了所有的平移缩放旋转操作都会影响到画布坐标系。那在我们对画布进行了一系列操作之后,怎么再知道当前矩阵数据状态呢。具体代码首先请看下面的一段代码(下文具体解释代码作用): 1 window.TrackTr ...
前言
在我的另一篇博文 Canvas坐标系转换 中,我们知道了所有的平移缩放旋转操作都会影响到画布坐标系。那在我们对画布进行了一系列操作之后,怎么再知道当前矩阵数据状态呢。
具体代码
首先请看下面的一段代码(下文具体解释代码作用):
1 window.TrackTransform = function () { 2 var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); 3 var xform = svg.createSVGMatrix(); 4 var savedTransforms = []; 5 this.trackTransform=function(ctx) { 6 7 ctx.getTransform = function () { return xform; }; 8 9 var save = ctx.save;10 ctx.save = function () {11 savedTransforms.push(xform.translate(0, 0));12 return save.call(ctx);13 };14 var restore = ctx.restore;15 ctx.restore = function () {16 xform = savedTransforms.pop();17 return restore.call(ctx);18 };19 20 var scale = ctx.scale;21 ctx.scale = function (sx, sy) {22 xform = xform.scaleNonUniform(sx, sy);23 return scale.call(ctx, sx, sy);24 };25 var rotate = ctx.rotate;26 ctx.rotate = function (deg) {27 28 var radians = deg * Math.PI / 180;29 xform = xform.rotate(deg);30 return rotate.call(ctx, radians);31 };32 var translate = ctx.translate;33 ctx.translate = function (dx, dy) {34 xform = xform.translate(dx, dy);35 return translate.call(ctx, dx, dy);36 };37 var transform = ctx.transform;38 ctx.transform = function (a, b, c, d, e, f) {39 var m2 = svg.createSVGMatrix();40 m2.a = a; m2.b = b; m2.c = c; m2.d = d; m2.e = e; m2.f = f;41 xform = xform.multiply(m2);42 return transform.call(ctx, a, b, c, d, e, f);43 };44 var setTransform = ctx.setTransform;45 ctx.setTransform = function (a, b, c, d, e, f) {46 xform.a = a;47 xform.b = b;48 xform.c = c;49 xform.d = d;50 xform.e = e;51 xform.f = f;52 return setTransform.call(ctx, a, b, c, d, e, f);53 };54 var pt = svg.createSVGPoint();55 //通过原坐标系点x,y求对应当前坐标系的坐标值56 ctx.transformedPoint = function (x, y) {57 pt.x = x; pt.y = y;58 return pt.matrixTransform(xform.inverse());59 }60 var pt2 = svg.createSVGPoint();61 //当前坐标系中的的xy还原到原坐标系坐标值62 ctx.transformedPoint2 = function (x, y) {63 pt2.x = x; pt2.y = y;64 return pt2.matrixTransform(xform);65 }66 var clearRect = ctx.clearRect;67 ctx.clearRect = function (x, y, w, h) {68 ctx.save();69 ctx.setTransform(1, 0, 0, 1, 0, 0);70 clearRect.call(ctx, x, y, w, h);71 ctx.restore();72 }73 }74 }
原标题:获取Canvas当前坐标系矩阵
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。