仿射变换矩阵偏移

Kev*_*ans 7 javascript graphics matrix affinetransform html5-canvas

这最近几天一直在杀我.甚至没有开玩笑,但我一直在努力解决这个问题.

我目前正在尝试使用仿射变换矩阵在HTML5中创建等轴投影.我收到的瓷砖是一个旋转45度的正方形(基本上是方形帆布上的方形钻石).然后,我根据x或y方向是否存在增量来缩放其中一个轴.然后我将轴倾斜一个因子来拟合.然后,我通过向后旋转-45度来否定初始旋转.

目前,我的仿射矩阵是:

      // note: the difference in z is about 10 in this example,
      //       so, xDiff is usually 40
      var xDiff  = 4 * (center.z   - map[x+1][y].land.z);
      var yDiff  = 4 * (center.z   - map[x][y+1].land.z);

      var matrix = multiplyAll(
        // Rotation
        [COS45,  SIN45,
         -SIN45, COS45],

        // Scale in each respective axis
        [(44+yDiff)/44, 0,
         0, (44+xDiff)/44],

        // Skew each axis
        [1,  -yDiff/(44+yDiff),
         -xDiff/(44+xDiff), 1],

        // Negate the rotation
        [NCOS45, NSIN45,
        -NSIN45, NCOS45]
      );
Run Code Online (Sandbox Code Playgroud)

然后我用它绘制它:

      // the map has its own x & y values which directions are determined by the red x & y arrows in the picture
      // pX & pY are the point relative to the canvas origin
      var pX = x * 22 - y * 22 + 22;
      var pY = y * 22 + x * 22 - 22 - (center.z * 4);
      context.setTransform(matrix[0], matrix[1],
                           matrix[2], matrix[3],

                           300, 100);

      //m_Context.drawImage(image, pX, pY);
      drawDiamond(pX, pY, true); // draws a 44x44 diamond
Run Code Online (Sandbox Code Playgroud)

投影测试

变形飞机

如您所见,变换后的矩阵是相对于变换后的x轴绘制的(我认为"新"x轴的斜率为yDiff/44).我不确定如何绘制形状,以便转换后的结果将处于正确的位置.使用pY = x * 22 - (yDiff/10);似乎更接近,但我通过插入随机数字几乎猜对了.

TL;博士:

  • 我进行了一次改造
  • 我有一个瓷砖应该是的坐标(如果没有变换)
  • 如何计算所需的偏移量,以便变换后的tile的坐标与未转换时的坐标相同?

PS:底部的怪异钻石现在可以忽略,因为它们可以正确创建,我发现如何计算偏移量.

lus*_*oog 4

仿射变换矩阵 ([abcdef]) 表示两个方程

x' = ax + cy + e
y' = bx + dy + f
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用偏移量ef绕过缩放和倾斜部分(嵌入 2x3 或 3x3 矩阵中的 4x4 线性变换)。

这在 postscript 编程中经常使用,其中用于绘制对象的坐标是相对于本地原点的。如果您要连接矩阵,请在缩放和倾斜之前进行平移,并且ef值将保持不变。