1

我正在围绕它的中心旋转一个 jCanvas 层,但之后我需要计算它的新 x 和 y 坐标。我正在使用下面的代码,尽管它返回错误的值:

var rotation = layer.rotate * Math.PI / 180;

//object's middle
var middleX = layer.x + layer.width / 2;
var middleY = layer.y + layer.height / 2;

//new coords (wrong)
var newX = middleX * Math.cos(rotation) - middleY * Math.sin(rotation);
var newY = middleX * Math.sin(rotation) + middleY * Math.cos(rotation);

对于简单的旋转 - 例如 90 度,我可以像这样得到新角的 x 和 y:

var middleX = layer.x + layer.width / 2;
var middleY = layer.y + layer.height / 2;
var newX = middleX - layer.height / 2;
var newY = middleY - layer.width / 2;

但是更复杂的情况呢?

编辑:

我找到了这个公式,但它只有在我顺时针旋转时才能正常工作。逆时针旋转呢?

var newX = (layer.x - middleX) * Math.cos(rotation) - (layer.y - middleY) * Math.sin(rotation) + middleX;
        var newY = (layer.x - middleX) * Math.sin(rotation) + (layer.y - middleY ) * Math.cos(rotation) + middleY;
4

2 回答 2

1

您即将围绕中心旋转并获得新的角坐标。假设您想获得角度不是 90 度的最大边界框:

var theta = layer.rotate*Math.PI/180.;

// Find the middle rotating point
var midX = layer.x + layer.width/2;
var midY = layer.y + layer.height/2;

// Find all the corners relative to the center
var cornersX = [layer.x-midX, layer.x-midX, layer.x+layer.width-midX, layer.x+layer.width-midX];
var cornersY = [layer.y-midY, layer.y+layer.height-midY, midY-layer.y, layer.y+layer.height-midY];

// Find new the minimum corner X and Y by taking the minimum of the bounding box
var newX = 1e10;
var newY = 1e10;
for (var i=0; i<4; i=i+1) {
    newX = min(newX, cornersX[i]*Math.cos(theta) - cornersY[i]*Math.sin(theta) + midX);
    newY = min(newY, cornersX[i]*Math.sin(theta) + cornersY[i]*Math.cos(theta) + midY);
}

// new width and height
newWidth = midX - newX;
newHeight = midY - newY;
于 2012-12-30T23:52:43.043 回答
-1
    var theta = layer.rotate*Math.PI/180.;
    // Find the middle rotating point
    var midX = layer.x+ layer.width/2;
    var midY = layer.y+ layer.height/2;
    // Find all the corners relative to the center
    var cornersX = [layer.x-midX, layer.x-midX, layer.x+layer.width-midX, layer.x+layer.width-midX];
    var cornersY = [layer.y-midY, layer.y+layer.height-midY, midY-layer.y, midY-(layer.y+layer.height)];
    // Find new the minimum corner X and Y by taking the minimum of the bounding box
    var newX = 1e10;
    var newY = 1e10;
    for (var i=0; i<4; i=i+1) {
        newX = cornersX[i]*Math.cos(theta) - cornersY[i]*Math.sin(theta) + midX
        newY = cornersX[i]*Math.sin(theta) + cornersY[i]*Math.cos(theta) + midY
    }
于 2013-09-28T11:15:10.890 回答