# 【HTML5 Canvas】计算元件/显示对象经过Matrix变换后在上级/舞台上的bounds（边界矩形rect）

`Matrix (a=0.4999847412109375, b=-0.865966796875, c=0.86602783203125, d=0.500030517578125, tx=-44.3, ty=6.8)`

```        var matrix = new Matrix2D();
matrix.rotate(-60*Math.PI/180);```

```    p._transformBounds = function (bounds, matrix) {
if(bounds.x || bounds.y){
matrix.append(1,0,0,1,bounds.x,bounds.y);
}

var lt = {x:0, y:0};
var rt = {x:bounds.width, y:0};
var lb = {x:0, y:bounds.height};
var rb = {x:bounds.width, y:bounds.height};

lt = transformPoint(matrix, lt);
rt = transformPoint(matrix, rt);
lb = transformPoint(matrix, lb);
rb = transformPoint(matrix, rb);

var minX = Math.min(lt.x, rt.x, lb.x, rb.x);
var minY = Math.min(lt.y, rt.y, lb.y, rb.y);
var maxX = Math.max(lt.x, rt.x, lb.x, rb.x);
var maxY = Math.max(lt.y, rt.y, lb.y, rb.y);

function transformPoint(m, p) {
return {x: m.a * p.x + m.c * p.y + m.tx, y: m.b * p.x + m.d * p.y + m.ty};
}

return new Rectangle(minX, minY, maxX - minX, maxY - minY);
};```

```    p._transformBounds = function(bounds, matrix) {
var x = bounds.x, y = bounds.y, width = bounds.width, height = bounds.height;
var mtx = new Matrix2D();
mtx.appendMatrix(matrix);
if (x || y) { mtx.append(1,0,0,1,x,y); }

var x_a = width*mtx.a, x_b = width*mtx.b;
var y_c = height*mtx.c, y_d = height*mtx.d;
var tx = mtx.tx, ty = mtx.ty;

var minX = tx, maxX = tx, minY = ty, maxY = ty;

if ((x = x_a + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; }
if ((x = x_a + y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; }
if ((x = y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; }

if ((y = x_b + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; }
if ((y = x_b + y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; }
if ((y = y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; }

return new Rectangle(minX, minY, maxX-minX, maxY-minY);
};```

```    p.test = function () {
var bounds = new Rectangle(-28, -35, 152, 128);
var matrix = new Matrix2D();
matrix.rotate(-60*Math.PI/180);
var t = this._transformBounds(bounds, matrix);
console.log(t);
};```

`Rectangle {x: -44.31088913245536, y: -124.88715006927039, width: 186.85125168440817, height: 195.6358613752347, initialize: function…}`

172 篇文章35 人订阅

0 条评论

## 相关文章

2.7K2

790

51210

1052

1853

1112

### 第98天：CSS3中transform变换详解

Transform字面上就是变形，改变的意思。在CSS3中transform主要包括以下几种：旋转rotate、扭曲skew、缩放scale和移动transla...

713

26910

1003

2327