旋转后计算新的x和y坐标

时间:2012-12-30 20:31:50

标签: jquery jcanvas

我正在围绕它的中心旋转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;

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:-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
    }